function
A function is a code segment that implements a certain function. It passes in parameters and returns values.
Python built-in function len, pass it a list, and it will return the length of the list (return value); The print function prints the incoming object to the screen. It does not return any value. We say it returns None; The return value of the input function is the string entered on the screen.
Function definition
Use the def keyword to define the function. The parameters are written in parentheses after the function name, and the return value is written after return. In order to understand the example of the parameter f passed in by the function, the following is an example of the parameter f passed in to facilitate the calculation
def f(x): # Function definition y = x * x return y a = int(input('Enter an integer:')) b = f(a) # function call print(a, 'The square of is', b)
Operation results
Enter an integer: 4 4 The square of is 16
The use of function can improve the modularity of application and the reuse rate of code.
Incoming parameters
Required parameters
There can be 0, 1 or more parameters written in parentheses after the variable name. How many parameters are specified when defining the function, and how many parameters are passed in when calling.
In the following example, define a function to print triangles and a function to print a line of strings
def print_line(t, symbol): print(symbol * t) def print_triangle(t, symbol): for x in range(1, t + 1): print_line(x, symbol) print_triangle(5, 'O')
Operation results
O OO OOO OOOO OOOOO
Default parameters
If the default parameters are set when defining a function, the corresponding parameters can not be passed in when calling the function, and the function will use the default parameters. The following example sets the default value of symbol to 5, so this parameter can not be passed in during function call
def print_line(t, symbol='#'): print(symbol * t) def print_triangle(t, symbol='#'): for x in range(1, t + 1): print_line(x, symbol) print_triangle(4) # Function uses default arguments symbol='#' print() # Empty line print_triangle(5, 'O')
Operation results
# ## ### #### O OO OOO OOOO OOOOO
The default parameters must be written after the required parameters and cannot be written as def print_line(symbol='#', t):
Return value
The object after return is called the return value. In actual programming, for functions with non empty return value, a variable is often used to receive the return value. When return is encountered, the function returns the return value and exits the function immediately. STR below_ The date function combines the passed in month, year and day into a time string, and then returns the time string.
def str_date(year, month, day): date = str(year) + '-' + str(month) + '-' + str(day) if day == 1: date += 'st' return date elif day == 2: date += 'nd' return date elif day == 3: date += 'rd' return date date += 'th' # When day < = 3, the function will not execute here return date d1 = str_date(2006, 6, 6) d2 = str_date(2003, 8, 1) print(d1, d2)
Operation results
2006-6-6th 2003-8-1st
If there is no return statement in the function body, the null value None is returned by default. Front print_triangle is a function that returns a null value.
function call
With function_name(...) The return value of non None is usually received by a variable, such as b = f(4)
Keyword parameters
When a parameter is passed in as a keyword parameter, the order in which the parameter is passed in can be different from the order in which the function is defined, because the Python interpreter can match the parameter value with the parameter name
def str_date(year, month, day): date = str(year) + '-' + str(month) + '-' + str(day) if day == 1: date += 'st' return date elif day == 2: date += 'nd' return date elif day == 3: date += 'rd' return date date += 'th' return date print(str_date(day=1, year=1949, month=10))
Operation results
1949-10-1st
Namespace
namespace is a mapping from name to object implemented by dictionary.
Simply put, when a Python program starts, a global namespace is created. The key value pair of the global namespace corresponds to the global variable and its stored value (function name and function object...). When a global variable is newly defined, the global namespace will add a key value pair from the variable name to the value of the variable. When modifying the value of a variable, the corresponding key value pair will also be modified in the global namespace. The globals function returns the global namespace (a dictionary)
>>> a = 1 >>> globals() {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 1}
The key 'a' of this dictionary corresponds to the value 1, that is, the defined a = 1. There are also some inherent key value pairs in the global namespace, which correspond to the existing global variables and the values (objects) it stores.
>>> print(__name__) __main__
When a function is called, a local namespace is created. The variable defined in the function is the local variable of the function. The locals function returns the current local namespace.
The following example defines a change function, tries to modify the value of the global variable in the function, and observes the local namespace and global namespace
>>> def change(): ... a = 2 ... print('Local namespace:', locals()) ... print('Global namespace:', globals()) ... print(a) ... >>> change() Local namespace: {'a': 2} Global namespace: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 1, 'change': <function change at 0x7f8c5c39cd30>} 2 >>> a 1
The change function did not successfully modify the value of the global variable because the Python interpreter thought that a = 2 was defining a local variable, so the key value pair 'a': 2 was added to the local namespace, but the key value pair 'a': 1 of the global namespace did not change. When accessing a variable, python first looks in the local namespace, then in the global namespace, and finally in the built-in namespace (built-in functions, variables...). This explains why print(a) in the function prints 2.
Global statements can be used to modify global variables in functions. Global statements can bind the specified variables to the global namespace
>>> def change(): ... global a ... a = 2 ... print('Local namespace:', locals()) ... print('Global namespace:', globals()) ... >>> change() Local namespace: {} Global namespace: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 2, 'change': <function change at 0x7f8c5c39cca0>} >>> a 2
In addition to using global statements, you can also directly modify the global namespace (Dictionary) to modify the value of global variables
>>> a = 1 >>> def change(): ... globals()['a'] = 2 # directly modify ... print('Local namespace:', locals()) ... print('Global namespace:', globals()) ... >>> change() Local namespace: {} Global namespace: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 2, 'change': <function change at 0x7f8c5c39cd30>} >>> a 2
Similarly, you can also modify (create) the value of a local variable in the form of locals()['name '].