Understand Python's global variables and local variables

PHP中文网
Release: 2017-06-20 15:52:01
Original
1549 people have browsed it

Understanding Python's global variables and local variables

1. If the variable name inside the defined function appears for the first time and precedes the = symbol, it can be considered to be defined as a local variable. In this case, regardless of whether the variable name is used in the global variable, the local variable is used in the function. For example:

# _*_ coding: utf-8 _*_
num = 110
def func():
    num = 1
    print(num)
func()
输出结果:1
Copy after login
# _*_ coding: utf-8 _*_
num = 110
def func():
    num += 1
    print(num)
func()
输出结果:
Copy after login

UnboundLocalError: local variable 'num' referenced before assignment

Error message: The local variable num is applied before assignment, that is, it is used without defining the variable, thus again It proves that a local variable is defined here instead of using the global num.

Summary: If the variable name inside the function appears for the first time and appears before =, it is regarded as defining a local variable.

2. If the variable name inside the function appears for the first time and appears after =, and the variable has been defined in the global domain, the global variable will be referenced here. If the variable does not exist in the global domain Definition, of course there will be a "variable is not defined" error. For example:

# _*_ coding: utf-8 _*_
num = 110
def func():
    num1 = num +  1
    print(num1)
func()
输出结果:
111

3、函数中使用某个变量时,该变量名既有全局变量也有同名的局部变量,则会使用局部变量,例如:
Copy after login
# _*_ coding: utf-8 _*_
num = 110
def func():
    num = 200
    num1 = num +  1
    print(num1)
func()
输出结果:
201
Copy after login
4、在函数中,如果想给全局变量赋值,则需要用关键字global声明,例如:
Copy after login
# _*_ coding: utf-8 _*_
num = 100
def func():
    num = 300
    num1 = num +  1
    print(num1)
func()
print num
输出结果:
Copy after login

301<br>100

declare num:

# _*_ coding: utf-8 _*_
num = 100
def func():
    global  num
    num = 300
    num1 = num +  1
    print(num1)
func()
print num
Copy after login
输出结果:
Copy after login

301<br>300

from:

<br>
Copy after login

The above is the detailed content of Understand Python's global variables and local variables. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template