Global and local variables in python

1. Definition

1. Global variables

Variables defined in the first-level code outside the function are called global variables and can be used globally.

2. Local variables

Variables defined in functions can only take effect locally

2. Usage

1. Global variables can be referenced inside the function. If both the global and the local have a variable name, the order in which the function looks for variables is from local to global.

2. A method cannot find a local variable of another method

 

3. Modify global variables in functions

name="aaa"
def guess():
  global name #Modify the global variable and change the global variable name to the name of the local variable
  name="bbb"
  print(name,id(name))
guess()
print(name,id( name))

 

Note: When the global variable is modified in the function, the global variable will change (except strings, numbers)

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326710921&siteId=291194637