The following is a function defined first:
Copy CodeThe code is as follows:
def foo ():
Print (' function ')
Foo ()
In the above code, a function named Foo is defined, and the function has no arguments. The function of the last line of code is to call this function. This is the simplest form of a function. Here's a description of the function with parameters:
Copy CodeThe code is as follows:
def foo ():
Print (' function ')
Def foo1 (A, B):
Print (A+B)
Foo ()
Foo1 (ON)
Foo1 is a function with parameters, which can be called using FOO1.
In a program, a variable exists, which involves the scope of the variable. In Python, the scope of a variable is three levels: global, local, and nonlocal.
Global: As the name implies, represents a globally variable. That is, this variable is at the highest level in Python, that is, the variable is defined at the highest level, not in a function or class.
Local: Locally variable, defined in the function.
Nonlocal: This is a relative concept. In Python, internal functions can be nested inside a function so that the variables inside the function are nonlocal relative to the inline function inside the function.
Below, give the relevant program to illustrate, first look at the global and local variables:
Copy CodeThe 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)
#************************
#运行结果
1
2
***********
3
3
***********
1
3
In the above program, two global variables x and y are defined, and a local variable x is defined inside the function foo. According to the running results, the variable x is the true local variable inside foo. Because the modifications to it do not affect the global variable X. In addition, if you need to use global variables inside foo, you need to use the Global keyword. The intent of global Y is to declare the variable y as an externally declared global variable Y. Therefore, when Y is modified within Foo, there is still influence outside of Foo. Because Foo modifies a global variable.
Let's take a look at nonlocal:
Copy CodeThe 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 ()
#**********
#运行结果
Inner function and z = 4
Out function and z = 4
Current 1/2 page
12 Next Page