A function is a block of formed, reusable code that is utilized to execute a single, related action. The functions in Python are deliberately produced better modularity for user-end applications along with a high degree of code reusing.
As you already know, Python delivers you many built-in functions like print(), etc. but you can also make your own functions. These functions are called user-defined functions.
def functionname( parameters ): "function_docstring" function_suite return [expression]
By default, parameters that have positional deeds and you need to inform them in the similar order that they were defined.
Example
1
The following function takes a string as an input parameter and prints it on a standard screen.
def printme( str ): "This prints a passed string into this function" print str return
Defining a function only supplies it a name, specifies the parameters that are to be incorporated in the function, and structured the blocks of code.
Once the essential preparation of a function is resolved, you can carry on it by calling it from another function or directly from the Python punctual. Following is the example to call printme() function :
#!/usr/bin/python # Function definition is here def printme( str ): "This prints a passed string into this function" print str return; # Now you can call printme function printme("I'm first call to user defined function!") printme("Again second call to the same function")
When the above code is executed, it supplies the following result:
I'm first call to user defined function! Again second call to the same function
Entire parameters (arguments) have been passed by orientation. It standards if users change what a parameter talks about to within a function, alter also reflects back in the calling function. For example :
#!/usr/bin/python # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist
Here, we are maintaining the reference of the passed object and appending values in the same object. So, this would produce the following result :
Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where the argument is being passed by reference and the reference is being overwritten inside the called function.
#!/usr/bin/python # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist = [1,2,3,4]; # This would assig new reference in mylist print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist
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:
#!/usr/bin/python # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist = [1,2,3,4]; # This would assig new reference in mylist print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist
You can call a reason by utilizing the subsequent types of formal arguments:
Needed rows are the arguments exceeded to a function in the right positional order. Here, the number of spats in the function call should match exactly with the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise, it gives a syntax error as follows:
#!/usr/bin/python # Function definition is here def printme( str ): "This prints a passed string into this function" print str return; # Now you can call printme function printme()
When the above code is executed, it produces the following result:
Traceback (most recent call last): File "test.py", line 11, in printme(); TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments are considered to the function calls. When users operate keyword arguments in a utility call, the caller recognizes the arguments by the parameter name.
This allows you to pass over arguments or place them out of order, as the Python interpreter is able to utilize the keywords distributed to match the values with parameters. You can also create keyword calls to the printme() function in the following ways:
#!/usr/bin/python # Function definition is here def printme( str ): "This prints a passed string into this function" print str return; # Now you can call printme function printme( str = "My string")
When the above code is executed, it produces the following result:
My string
The following example gives a more clear picture. Note that the order of parameters does not matter.
#!/usr/bin/python # Function definition is here def printinfo( name, age ): "This prints a passed info into this function" print "Name: ", name print "Age ", age return; # Now you can call printinfo function printinfo( age=55, name="niki" )
When the above code is executed, it produces the following result :
Name: niki Age 55
A default argument is an argument that assumes a default value if a value is not supported in the function call for that argument. The following instance gives an idea of default arguments, it prints default age if it is not passed:
#!/usr/bin/python # Function definition is here def printinfo( name, age = 25 ): "This prints a passed info into this function" print "Name: ", name print "Age ", age return; # Now you can call printinfo function printinfo( age=55, name="niki" ) printinfo( name="niki" )
When the above code is executed, it produces the following result:
Name: niki Age 55 Name: niki Age 25
You may necessitate processing a function for fewer arguments than users specified while defining the function. These developments are called variable-length arguments and named in the function definition, different needed and default arguments.
The syntax for a function with non-keyword variable arguments is this :
def functionname([formal_args,] *var_args_tuple ): "function_docstring" function_suite return [expression]
An asterisk (*) is placed before the variable name that holds the values of all non keyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example:
#!/usr/bin/python # Function definition is here def printinfo( arg1, *vartuple ): "This prints a variable passed arguments" print "Output is: " print arg1 for var in vartuple: print var return; # Now you can call printinfo function printinfo( 10 ) printinfo( 70, 60, 50 )
When the above code is executed, it produces the following result:
Output is: 10 Output is: 70 60 50
These functions are known anonymous since they are not stated in the standard manner by utilizing the def keyword. Users could be utilized the lambda keyword to generate small anonymous functions.
The syntax of lambda functions contains only a single statement, which is as follows :
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works:
#!/usr/bin/python # Function definition is here sum = lambda arg1, arg2: arg1 + arg2; # Now you can call sum as a function print "Value of total : ", sum( 10, 20 ) print "Value of total : ", sum( 20, 20 )
When the above code is executed, it produces the following result:
Value of total : 30 Value of total : 40
The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as a return of None.
All the above examples are not returning any value. You can return a value from a function as follows:
#!/usr/bin/python # Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2 print "Inside the function : ", total return total; # Now you can call sum function total = sum( 10, 20 ); print "Outside the function : ", total
When the above code is executed, it produces the following result:
#!/usr/bin/python # Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2 print "Inside the function : ", total return total; # Now you can call sum function total = sum( 10, 20 ); print "Outside the function : ", total
Not all variables in a program may be nearby at all locations in that program. This depends on where you have announced a variable. The scope of a variable concludes the portion of the program where users can admission an exacting identifier.
There are two basic scopes of variables in Python:
Variables that are identified inside a function cadaver have a local scope, and those described outside have a global extent.
This signifies that local variables can be contacted only within the function in which they are stated, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables stated inside it are brought into range. Following is a simple example
#!/usr/bin/python total = 0; # This is global variable. # Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2; # Here total is local variable. print "Inside the function local total : ", total return total; # Now you can call sum function sum( 20, 30 ); print "Outside the function global total : ", total
When the above code is executed, it produces the following result:
Inside the function local total : 50 Outside the function global total : 0
Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.