Home  >  Article  >  Backend Development  >  The difference between python global variables and local variables

The difference between python global variables and local variables

angryTom
angryTomOriginal
2020-02-29 13:48:2114034browse

The difference between python global variables and local variables

The difference between global variables and local variables is the scope, global variables are in the entire py file Declared, it can be used in the global scope; local variables are declared inside a function and can only be used inside the function. If they exceed the scope of use (outside the function), an error will be reported.

Recommended: Python Tutorial

#!/usr/bin/python3
# -*- coding: utf-8 -*-

A = 100 # 全局变量一般用大写字母表示

def func():
    a = 50 # 局部变量一般用小写字母表示
    print(a+A)

func()
print(A)
print(a) # 报错信息NameError: name 'a' is not defined

The difference between python global variables and local variables

#!/usr/bin/python3
# -*- coding: utf-8 -*-

A = 100

def func():
    A=250
    print(A)

print(A)    # 打印全部变量
func()      # 局部变量

The difference between python global variables and local variables

If you want to change global variables inside a function , you need to add the global keyword in front. After the function is executed, the global variable value will also change.

#!/usr/bin/python3
# -*- coding: utf-8 -*-
A = 100

def func():
    global  A
    A = 200
    print(A)


print(A)    # 打印全局变量
func()      # 局部变量
print(A)   # 改变后的全局变量

If the global variable is a list type, the list can be modified through the list method, and it can be declared without global.

list_1 = [1,2,56,"list"]

def changeList():
    list_1.append("over")
    print(list_1)

changeList()
print(list_1)

The difference between python global variables and local variables

Within the function, if the local variable has the same name as the global variable, the local variable will be called first.

Many python video tutorials, all on the PHP Chinese website, welcome to learn online!

The above is the detailed content of The difference between python global variables and local 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