7) Functions
1-Function is defined using the def keyword.
2-Arguments/parameters:
Arguments/parameters are specified in parenthesis after function name.
n number of arguments can be added.
3- function_docstring is optional.
4-return exists a fucntion
# Python fucntion syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
# simple python function
def hi():
print ('hello')
hi() #to call function
Pass by reference vs value:
Parameters/arguments in Python are passed by reference.
Means if you change what a parameter refers to within a function, change also reflects back in the calling function.
# Pass by reference vs value
def paas_by_ref( mylist,mylist1 ):
"This changes a passed list into this function"
mylist.append([1,2,3]);
mylist1.extend([1,2,3]);
print ("Values inside function: ", mylist)
print ("Values inside function mylist1: ", mylist1)
return
# calling paas_by_ref function
mylist = [10,20,30];
mylist1 = [10,20,30];
paas_by_ref( mylist, mylist1 );
# paas_by_ref( );
print ("Values outside function: ", mylist)
print ("Values outside function mylist1: ", mylist1)
Return statement:
def return_func( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print ("Inside function : ", total)
return total;
# # Now you can call sum function
return_func( 10, 20 );
Function Arguments:
You can call a function by using following types of arguments:
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
# Required arguments
def args_func( str ):
"This prints a passed string into this function"
print (str)
return;
# Now you can call printme function
args_func() # pass args here otherwise gets error
# keyword arguments
def args_func (name1, name2):
"This prints a passed info into this function"
print ("Name1: ", name1)
print ("NAme2: ", name2)
return;
# Call function
args_func (name1='a', name2="b")
# Default argumentsdef keyword_args (name1, name2='b'): "This prints a passed info into this function" print ("Name1: ", name1) print ("NAme2: ", name2) return;
# Call functionkeyword_args (name1='a')
# Default arguments
def keyword_args (name1, name2='b'):
"This prints a passed info into this function"
print ("Name1: ", name1)
print ("NAme2: ", name2)
return;
# Call function
keyword_args (name1='a')
# Variable length arguments
def args_func (name1, *name2):
"This prints a passed info into this function"
print ("Name1: ", name1)
print ("Name2: ", name2)
return;
# Call function
# for *name2, we can pass 0 or n args
args_func ('a')
No comments:
Post a Comment