Functions are modules that perform a specific set of operations. Functions can take input in the form of arguments and return results of various built-in or user-defined data types.
We can indicate a function by def keyword. In the example below I have declared and defined a function by name sum. It takes 2 arguments a and b. It returns the addition of a and b as a result. We call a and b as arguments of the function. We have a return statement to pass the result c back to the calling function.
def sum( a, b):
c= a+b
return c
sum(1,2)
#output
3
For the same function, I call it with string parameters.
def sum( a, b):
c= a+b
return c
sum("hello"," Knowledge Seekers")
#output
'hello Knowledge Seekers'
Table of Contents
Scope and lifetime of the variables inside the function
I would discuss about the scope of a variable with the example below.
def GetValue():
var = "Inside function"
print(var)
var = "Outside Function"
GetValue()
print(var)
We have a function called GetValue that has a variable called var. Now you can see that var has a string value saying “Inside function”. There is another variable called var outside the function with a value “Outside Function”. When I print var outside of the function its value will not be updated because the other value is out of scope. The scope of var inside the function stays inside. Once the control comes out of that function the value of var which exists in that scope is retained. Hence we can say that the values inside the scope of the function will exist only inside the function.
Default argument
We can specify a value as default for one or more arguments in the function, for instance.
def multiply( a , b=5):
c= a*b
return c
multiply(34)
#output
170
In the example above, I specified that the value of b will have a default of 5. When I call the function I can call it with a single argument and let the default be considered. Thus by multiplying 34*5 we get the result 170.
Example to pass list to a function
We can pass a list, dictionary, tuple, or any data type as an argument into the function. I am passing an integer list into the printList function and printing them inside it.
def printList(intList):
for item in intList:
print(item)
intList = [2,4,5,6,89,0]
printList(intList)
#output
2
4
5
6
89
0
This concludes my tutorial on functions. Feel free to comment on the functions you are thinking about.