Function Defining and Calling in Python
In this class, we discuss function defining and calling in python.
For Complete YouTube Video: Click Here
Need of Function
Before going into the concept of function, first, understand the need of the function.
Let’s take an example and understand the need for function. The reader should have basics about the list, string, and all the loops concepts. Click here.
Example:
Sum all the elements in the given lists.
a=[1,2,5,7,8,9]
b=[11,12,13,14]
c=[21,25,22,26]
sumvalue=0
for i in a: # sum first list
sumvalue=sumvalue+i
print(sumvalue)
sumvalue=0
for j in b: # sum second list
sumvalue=sumvalue+j
print(sumvalue)
sumvalue=0
for k in c: # sum third list
sumvalue=sumvalue+k
print(sumvalue)
From the above program, we noticed that the same code written three times.
Iterate on the list using loop and each time sum the value with the previously calculated sum.
The same code repeated for all the lists.
In this type of situations, we can use functions. We write the code once in the function. And use the same code on different inputs.
Below we explain how to modify the code using functions.
Function Defining and Calling
The below program shows us the implementation of the sum of elements in the lists using functions.
# use of Function
a=[1,2,5,7,8,9]
b=[11,12,13,14]
c=[21,22,25,26]
# define a function
def f(x):
sumvalue=0
for i in x:
sumvalue=sumvalue+i
print(sumvalue)
f(a)# calling function with input parameter a
f(b)# calling function with input parameter b
f(c)# calling function with input parameter c
Function definition starts with def and followed by function name and list of parameters.
def f(x): here f is function name. we can give any name.
x is the parameter name. We discuss function parameters later in this class.
Calling a function is done like this f(a) in the above program.
Here we called the function, and the input sent to the function a.
List a is now passed as an argument to function f.Ie. The parameter x in function f takes the reference of the list a.
Whenever we called the function, the function code will get executed using the input parameters passed to the function.
Again we are calling the function using list b. f(b) shown in the above program.
Again function executes with this new input. And the sum value is displayed.
The same code we are using for different inputs. It is the benefit of using functions.