This tutorial explains user-defined functions in Python.
How to define a function
def
keyword is used to create a user defined function.
def functionname(arguments):
# function body
#code statements 1
#code statements 2 to N
For example, Define a function
def add(m,n):
return m+n;
- add is a function name
- m,n are arguments to function
- return keyword returns the result from a function
Once the function defined, Call the function with arguments
result=add(1,2)
print(result);#3
Functions with multiple return values
Ideally, Functions might return multiple values.
Here is an example
def calculate(m,n):
sum=m+n
average=(m+n)/2
return sum,average;
sum,average=calcuate(6,2)
print(sum);v #8
print(average);#4.0
How to declare a function with default arguments.
Functions can declare multiple arguments, the Caller has to pass all arguments.
Sometimes, the Caller does not pass all arguments, function receives a nil value for not-passed values.
In that case, the Function can be declared with default arguments
Here is an example
def calcuate(m,n=4):
sum=m+n
average=(m+n)/2
return sum,average;
sum,average=calcuate(6,2)
print(sum); #8
print(average);#4.0
sum1,average1=calcuate(6)
print(sum1);#10
print(average1);#5.0