Milandeep Bassi

Defining and Calling Functions in Python Programming

10th, February, 2020


Functions

They're a way to re-use code efficiently. A way to neatly organise code and to separate the code into self-contained sections or files. 

A function makes it when you need some code that can be re-used or is to complicated to store within the main body of code you separate it into a function. For example if we're trying to calculate the area of a circle instead of typing area = 3.14 * radius ** 2 each time we could create a function to calculate this for us. 

def CircleArea(radius):
area = 3.14 * radius ** 2
return area

By doing this what we're gonna do is get the user to enter a radius into the program and then use this in the function to return the area. In an application it would look like this. 

def CircleArea(radius):
area = 3.14 * radius ** 2
return area

r = int(input("Enter the radius of circle: "))
print("Circle area: ", CircleArea(r))

>>>
Enter the radius of circle: 12
Circle area: 452.16
>>>

 The function name is equally as restricted as a variable name. Another type of function is one that processes the data and then prints an output rather than returning a value to the program. 

def functionName ( parameters ):
function_code
function_code
...
return [expression]

In a function it is possible to have zero parameters, one parameter or many more. It is possible to pass a variety of data types through the function. However we do have to consider some things when passing through a function.

If the variable we're passing through the function is immutable then python will pass a copy of the variable through the function. This includes items such as strings, numerical values, tuples.

However if the variable is mutable then the python actually passes a reference to the variable. So this means when the variable inside the function changes it will also change outside the function. This includes items such as lists, dictionaries.