Functions can defined as a block of reusable statements that performs single or related actions.It helps to break programs into smaller chunks and generates result in a organized manner.
Rules for defining Function:
->Function should always begin with the keyword "def" followed by function name and paranthesis.
->values should be passed using paraments or arguments which are defined within the paranthesis.
->A colon (:) should be used to mark the end of function header.
->The documentation string or docstring is optional in function.
->Statements defined in function shpuld have same identation levels.
->It is option to return value from function.
def printme( str ):
"This prints a passed string into this function"
Calling a Function:
Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is the example to call printme() function -
print("1st call for function")
print("2nd call for function")
When the above code is executed, it produces the following result -
1st call for function
2nd call for function
Pass by reference vs value:
All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example -
There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function.
def change( list ):
list = [10,20,30,40]; # new reference in list
print "Values inside: ", list
# Now you can call changeme function
list = [9,8,7];
change( list );
print "Values outside: ", list
The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result: