Functions
Functions
agenda
Why to use function?
Function definition
Function call
example
Why to use function?
Easier to read and debugging
Reusability
Dividing long program into functions
What are functions?
Syntax :
def function_name(parameters):
statement(s)
Functions in python
Function definition:
o every function should start with “def”
keyword
o Name of the function
o Parameters/arguments(optional)
o Function name should end with :
o Return (empty or value)
o Multi value return can done(using tuples)
Function call
Function name
Arguments and parameters
Example for function
#example for function in python
# function definition
def add(num1, num2):
sum=num1+num2
return sum
#actual code
def swap(num1,num2):
temp=num1
num1=num2
num2=temp
print("after swapping num1 and num2is:",num1,num2)
#actual code
display(100,200)
Keyword arguments
Oder or position is not required
Initialization done base of keywords
Example:
#expample for keyword arguement
def display(num1,num2):
print(num1,num2)
display(num2=10, num1=20)
Default arguments
Number of argument need not be same
Some of arugements will be consider as default
Example:
#example for default arguements
display(name="robert",course="BCA")
display(name="rishab")
Variable length arguments
Arbitrary number of arguments
By placing * as prefix to the arguments of function
definition:
Example:
#example for variable arguements
def display(*course):
for i in course:
print(i)
display("MCA","BCA","M.Tech","B.E")