1. Definition and Grammar
Python defines functions using the def keyword. The general format is as follows:
def function name (parameter list): function body
def area(width, height): return width * height
You can define a function that does what you want, the following are simple rules:
- A function code block begins with the def keyword, followed by the function identifier name and parentheses () .
- Any incoming parameters and arguments must be placed between parentheses, which can be used to define parameters.
- The first line of statements in a function can optionally use a docstring—for function descriptions.
- Function content starts with a colon and is indented.
- return [expression] Ends the function, optionally returning a value to the caller. return without an expression is equivalent to returning None.
1 # !/usr/bin/python3 2 3 #define function 4 def printme ( str ): 5 " print any string passed in " 6 print (str); 7 return ; 8 9 #call function 10 printme( " I To call a user-defined function! " ); 11 printme( " Call the same function again " );
The parameters of the function
In python, strings, tuples, and numbers are immutable objects, while lists, dicts, etc. are modifiable objects.
-
Immutable type: assign a=5 to the variable and then assign a=10 , here is actually a newly generated int value object 10, and then let a point to it, and 5 is discarded, not changing the value of a, which is equivalent to newly generating a .
-
Variable type: variable assignment la=[1,2,3,4] and then assigning la[2]=5 is to change the value of the third element of list la, la itself does not move, just a part of its internal value has been modified.
Argument passing for python functions:
-
Immutable types: C++-like passing by value, such as integers, strings, tuples . Such as fun(a), only the value of a is passed, and it does not affect the a object itself. For example, modifying the value of a inside fun(a) only modifies another copied object and does not affect a itself.
-
Mutable types: C++-like pass-by-reference, such as lists , dictionaries . For example, fun(la) means that the la is passed to the past, and the la outside the fun will also be affected after the modification.
Everything in python is an object, strictly speaking, we can't say pass by value or pass by reference, we should say pass immutable objects and pass mutable objects.
The following are the formal parameter types that can be used when calling a function:
- Required parameter
- keyword arguments
- default parameters
1 # !/usr/bin/python3 2 3 #Writable function description 4 def printinfo( name, age = 35 ): 5 " Print any string passed in " 6 print ( " name: " , name); 7 print ( " age: " , age); 8 return ; 9 10 #call printinfo function 11 printinfo( age=50, name= " runoob " ); 12 print ( " -------------- ------------") 13 printinfo( name="runoob" );
- variable length parameter
Variable names with an asterisk (*) hold all unnamed variable arguments. If no arguments are specified when the function is called, it is an empty tuple. We can also not pass unnamed variables to the function. The following example:
1 # !/usr/bin/python3 2 3 #Writable function description 4 def printinfo( arg1, * vartuple ): 5 " Print any arguments passed in " 6 print ( " Output: " ) 7 print (arg1) 8 for var in vartuple: 9 print (var) 10 return ; 11 12 #call printinfo function 13 printinfo( 10 ); 14 printinfo( 70, 60, 50 );
The output of the above example is:
Output: 10 Output: 70 60 50
Third, global variables and local variables
Variables defined inside a function have a local scope, and variables defined outside a function have a global scope.
Local variables can only be accessed within the function in which they are declared, while global variables can be accessed program-wide. When the function is called, all variable names declared inside the function will be added to the scope.
Fourth, anonymous function lambda
#!/usr/bin/python3
# Writable function description sum = lambda arg1 , arg2 : arg1 + arg2 ; # Call the sum function print ( "The added value is: " , sum ( 10 , 20 )) print ( "The added value is: " , sum ( 20 , 20 ))
5. Variable scope
The scope of a variable determines which part of the program can access which particular variable name. There are 4 types of scopes in Python, they are:
- L (Local) local scope
- E (Enclosing) in the function outside the closure function
- G (Global) global scope
- B (Built-in) built-in scope
Six, global and nonlocal keywords
The global and nonlocal keywords are used when the inner scope wants to modify a variable in the outer scope.
1 #!/usr/bin/ python3 2 3 num = 1 4 def fun1(): 5 global num # need to declare with global keyword 6 print(num) 7 num = 123 8 print(num) 9 fun1()
If you want to modify variables in nested scopes (enclosing scopes, outer non-global scopes), you need the nonlocal keyword, as in the following example:
1 # !/usr/bin/python3 2 3 def outer(): 4 num = 10 5 def inner(): 6 nonlocal num # nonlocal keyword declaration 7 num = 100 8 print (num) 9 inner() 10 print ( num) 11 outer()