Home  >  Article  >  Backend Development  >  Scope of python variables

Scope of python variables

silencement
silencementOriginal
2019-06-10 15:51:452876browse

Scope of python variables

Variable scope:

Generally, variables defined outside the function become global variables, and variables defined inside the function are called local variables.

Global variables are readable in all scopes, and local variables can only be read in this function.

When the function reads variables, it first reads the local variables of the function itself, and then goes to Read global variables

Global variables

Read, all can be read

Assignment, global

Dictionary, list can be modified

Global variables are all in uppercase letters

For example

name = 'Tim' #全局变量

def f1():
    age = 18 #局部变量
    print(age,name)

def f2():
    age=19 #局部变量
    print(age,name)

f1()
f2()
>>>
18 Tim
19 Tim

Global variables can also be defined inside a function:

name = 'Tim' #全局变量

def f1():
    age = 18 #局部变量
    global name #定义全局变量
    name = 'Eric'
    print(age,name)
f1()
print(name)

Global variables are readable by default and can be changed if needed The value of a global variable needs to be defined using global inside the function

Special: list, dictionary, can be modified, but cannot be reassigned. If reassignment is required, global variables need to be defined using global inside the function

NAME = ['Tim','mike'] #全局变量
NAME1 = ['Eric','Jeson'] #全局变量
NAME3 = ['Tom','jane'] #全局变量

def f1():
    NAME.append('Eric') #列表的append方法可改变外部全局变量的值
    print('函数内NAME: %s'%NAME)
    NAME1 = '123' #重新赋值不可改变外部全局变量的值
    print('函数内NAME1: %s'%NAME1)
    global NAME3 #如果需要重新给列表赋值,需要使用global定义全局变量
    NAME3 = '123'
    print('函数内NAME3: %s'%NAME3)
f1()
print('函数外NAME: %s'%NAME)
print('函数外NAME1: %s'%NAME1)
print('函数外NAME3: %s'%NAME3)
>>>
函数内NAME: ['Tim', 'mike', 'Eric']
函数内NAME1: 123
函数内NAME3: 123
函数外NAME: ['Tim', 'mike', 'Eric']
函数外NAME1: ['Eric', 'Jeson']
函数外NAME3: 123

The above is the detailed content of Scope of python variables. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn