In Python, functions are reusable program segments. You can use the def keyword to define a function. The following defines a function:
The code is as follows:
Def foo ():
Print ('function ')
Foo ()
In the above code, a function named foo is defined, which has no parameters. The function of the last line of code is to call this function. This is the simplest form of a function. The following describes the functions with parameters:
The code is as follows:
Def foo ():
Print ('function ')
Def foo1 (a, B ):
Print (a + B)
Foo ()
Foo1 (1, 2)
Foo1 is a function with parameters. you can use foo1 (1, 2) to call this function with parameters.
In a program, if a variable exists, the scope of the variable will be involved. In Python, the variable scope has three levels: global, local, and nonlocal.
Global: global variable, as its name implies. That is, this variable is at the highest level in python, that is, the definition level of this variable is the highest, rather than in functions or classes.
Local: a local variable, which is defined in a function.
Nonlocal: this is a relative concept. In python, internal functions can be nested to define internal functions. in this way, the internal variables of a function are nonlocal compared to built-in functions of the function.
The following describes the related procedures. First, let's take a look at global and local variables:
The code is as follows:
X = 1
Y = 2
Def foo (x ):
Print (x)
Print (y)
Print ('***********')
X = 3
Global y
Y = 3
Print (x)
Print (y)
Print ('***********')
Foo (x)
Print (x)
Print (y)
#************************
# Running result
1
2
***********
3
3
***********
1
3
In the above program, two global variables x and y are defined. inside the function foo, a local variable x is also defined. According to the running results, the variable x is a real local variable within foo. The modification does not affect global variable x. In addition, if you need to use global variables inside foo, you need to use the global keyword. The intention of global y is to declare the variable y as the global variable y that has been declared externally. Therefore, after foo modifies y internally, it still has an impact on the foo exterior. Foo modifies global variables.
Let's take a look at nonlocal:
The code is as follows:
Def out ():
Z = 3
Def inner ():
Nonlocal z
Z = 4
Print ('inner function and z = {0} '. format (z ))
Inner ()
Print ('out function and z = {0} '. format (z ))
Out ()
#**********
# Running result
Inner function and z = 4
Out function and z = 4
Current 1/2 page12 Next page