A function is an organized, reusable code used to perform a single, related action block. Functions provide a better module for the height of application and code reuse.
As we know, Python has many built-in functions such as print (), but it can also create its own functions. These functions are called user-defined functions.
Define a function
Functions can be defined to provide the required functionality. The following is a simple rule to define a Python function.
- The function block starts with the keyword DEF followed by the letter name and parentheses (()).
- Any input parameters or parameters should be placed within these parentheses. You can also define the parameters within these parentheses.
- The first statement of a function can be?? An optional declaration-a document string for the function or document string.
- The block of code in each function begins with a colon (:) and is indented.
- The statement returns the [expression] Exit function, optionally passing back an expression to the caller. The return statement without a parameter returns none.
Grammar:
def functionname (parameters): "function_docstring" function_suite return [expression]
By default, parameters have a position of behavior and need, and they are defined as notifying them in the same order.
Example:
This is the simplest form of Python function. This function takes a string as an input parameter and prints the standard screen.
def printme (str): "This prints a passed string to this function" print str return
Calling functions
Define a function to give its name only, specifying the parameters to be included in the function and structure of the code block.
Once the basic structure of the function is determined, it can be executed by invoking it from another function or directly from the Python prompt. The following is an example call to the Printme () function:
#!/usr/bin/python# function definition is heredef printme (str): ' This prints a passed string to this Function '
print str; return;# now can call Printme functionprintme ("I-m first call to User Defined function!"); Printme ("Again second call to the same function");
When executing the above code, the following results are produced:
I ' m first call to User defined function! Again second call to the same function
Reference vs Value passing
All parameters (parameters) in the Python language are passed by reference. This means that if you change the value of a parameter in a function, the change is reflected in the calling function. For example:
#!/usr/bin/python# function definition is heredef changeme (mylist): ' This changes a passed list to this Function ' C1/>mylist.append ([1,2,3,4]); Print "Values inside the function:", MyList return# Now you can call changeme functionmylist = [10,20,30];changeme (M ylist);p rint "Values outside the function:", mylist
Here, we keep a reference to the object being passed and append the value to the same object. In this way, this produces the following results:
Values inside the function: [1, 2, 3, 4]]values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is also an example of a parameter being overridden in a called function by reference passing and referencing.
#!/usr/bin/python# function definition is heredef changeme (mylist): ' This changes a passed list to this Function ' C1/>mylist = [1,2,3,4]; # This would assig new reference in MyList print "Values inside the function:", MyList return# Now you can call C Hangeme functionmylist = [10,20,30];changeme (mylist);p rint "Values outside the function:", mylist
The local function changeme on the parameter mylist. Changing the mylist within a function does not affect mylist. function does not work, and finally this results in the following:
Values inside the function: [1, 2, 3, 4]values outside the function: [10, 20, 30]
Function parameters:
You can call a function by using the type of the formal parameter as follows:
- Required Parameters
- Keyword parameters
- Default parameters
- Variable length parameters
Required Parameters:
The required parameters are parameters that are passed to the correct positional order of the function. Here, the number of arguments in the function call should exactly match the function definition.
Call the function Printme (), be sure to pass a parameter, or you will give a syntax error as follows:
#!/usr/bin/python# function definition is heredef printme (str): ' This prints a passed string to this Function '
print str; return;# now can call Printme Functionprintme ();
When the above code is executed, the following results are produced:
Traceback (most recent): File "test.py", line one, in
printme (); Typeerror:printme () takes exactly 1 argument (0 given)
Keyword parameters:
The keyword argument is related to a function call. When a keyword argument is used in a function call, the caller identifies the parameter by the parameter name.
This can skip parameters or out of order, because the Python interpreter can use the supplied parameters to use the keyword that matches the value. You can also make the keyword call the Printme () function in the following ways:
#!/usr/bin/python# function definition is heredef printme (str): ' This prints a passed string to this Function '
print str; return;# now can call Printme functionprintme (str = "My string");
When executing the above code, the following results are produced:
My string
The following example gives a clearer picture. Please note that this is not related to the parameter order.
#!/usr/bin/python# Function definition is heredef printinfo (name, age): ' This prints a passed info to this functio N " print" name: ", name; Print "Age", age; return;# now can call Printinfo Functionprintinfo (age=50, name= "Miki");
When the above code is executed, the following results are produced:
Name:mikiage 50
Default parameters:
The default parameter is a parameter that assumes a default value if the parameter value is not provided by the function call. The following example gives the default parameter an idea, which prints the age by default if it does not pass the value:
#!/usr/bin/python# Function definition is heredef printinfo (name, age = +): "This prints a passed info to this FU Nction " print" name: ", name; Print "Age", age; return;# now can call Printinfo Functionprintinfo (age=50, name= "Miki");p Rintinfo (name= "Miki");
When the above code is executed, the following results are produced:
Name:mikiage 50name:mikiage 35
Variable length parameters:
You may need to handle a function to specify more than one parameter in a defined function. These parameters are called variable length parameters, and the function definition is not named, unlike a required default parameter.
The general syntax for functions with non-keyword mutable parameters is this:
def functionname ([Formal_args,] *var_args_tuple): "function_docstring" function_suite return [ Expression
The asterisk (*) is placed and will hold the value of all non-keyword variable arguments before the variable name. The tuple remains empty if no other parameters are specified during the function call. The following is a simple example:
#!/usr/bin/python# Function definition is heredef printinfo (arg1, *vartuple): "This prints a variable passed argumen TS " print" Output is: " print arg1 for var in vartuple: print var return;# now can call Printinfo Functionprintinfo;p Rintinfo (70, 60, 50);
When the above code is executed, the following results are produced:
Output Is:10output is:706050
Anonymous functions:
You can use the Lambda keyword to create small anonymous functions. These functions are called anonymous because they are not declared in the standard way by using the DEF keyword.
- The lambda form can take any number of arguments, but returns only one value in the expression form. They cannot contain commands or multiple expressions.
- Anonymous functions cannot call printing directly because a lambda expression is required.
- A lambda function has its own namespace and cannot access variables higher than its argument list and those in the global namespace.
- Although it seems that lambda is a single-line version of a function, they are not in C or C + +, and their purpose is to call a declaration of a row on the stack of the transfer function by calling for performance reasons.
Grammar
The syntax for a lambda function contains only a single statement, as follows:
Lambda [arg1 [, Arg2,..... argn]]:expression
Here is an example of how the function lambda form works:
#!/usr/bin/python# Function definition is heresum = lambda arg1, arg2:arg1 + arg2; # Now you can call sum as a Functionprint "value of total:", sum (Ten) print "Value of total:", sum (20, 20)
When the above code is executed, the following results are produced:
Value of Total:30value of total:40
Return statement:
The statement returns the [expression] Exit function, optionally passing back an expression to the caller. The return statement without a parameter returns none.
All of the above examples do not return any values, but if you like, you can return a value from a function:
#!/usr/bin/python# Function definition is heredef sum (arg1, arg2): # ADD Both the parameters and return them. " Total = arg1 + arg2 print "Inside the function:"
When the above code is executed, the following results are produced:
Inside the Function:30outside the function:30
Scope of the variable:
All variables in the program may not be accessible from all locations in the program. This depends on the variable being declared.
The scope of a variable determines the program that can access part of a particular identifier. The variables in Python are two basic categories:
- Global variables
- Local variables
Global vs. local variables:
This is a function in which variables defined internally have a local scope, and those outside the definition have a global scope.
Local variables can only be declared and accessed within a function, while global variables may be accessed by all functions throughout the program body. When a function is called, the variables declared inside it are included in the scope. The following is a simple example:
#!/usr/bin/pythontotal = 0; # This was global variable.# Function definition is heredef sum (arg1, arg2): # ADD Both the parameters and return the M. " Total = Arg1 + arg2; # Here are the local variable. Print "Inside the function local total:"
When the above code is executed, the following results are produced:
Inside the function local total:30outside the function global total:0