Python-变量范围
时间:2020-02-23 14:43:16 来源:igfitidea点击:
在本教程中,我们将学习Python中变量的范围。
变量的范围是什么?
我们在Python程序中创建的变量并非随处可见。
它们的范围定义了我们可以访问它们的范围。
有两类可变范围。
- 全局变量范围
- 局部变量范围
什么是全局变量?
在任何函数外部定义的变量称为全局变量。
全局变量可以在给定函数的内部和外部访问。
在下面的Python程序中,我们将创建一个全局变量,并在函数内部和外部访问它。
# global variable score = 10 print("global variable score:", score) # func def foo(): print("value of score from inside foo():", score) # calling foo foo()
上面的代码将为我们提供以下输出。
global variable score: 10 value of score from inside foo(): 10
什么是局部变量?
在函数内部创建的变量称为局部变量。
我们无法在函数外部访问局部变量。
在下面的Python程序中,我们在函数内部创建一个局部变量。
# func def foo(): x = 10 print("local variable x:", x) # function call foo()
上面的代码将给出以下输出。
local variable x: 10
尝试在函数外部访问局部变量将引发错误。
在函数内部屏蔽全局变量
我们可以通过创建同名变量来屏蔽函数内部的全局变量。
在下面的Python程序中,我们将创建一个全局变量,然后通过在函数内部创建一个具有相同名称的局部变量来对其进行屏蔽。
# global variable x = 10 print("global variable x before function call:", x) # func def foo(): # local variable x = 20 print("local variable x inside foo():", x) print("function call") foo() print("global variable x after function call:", x)
上面的代码将打印以下输出。
global variable x before function call: 10 function call local variable x inside foo(): 20 global variable x after function call: 10
从函数内部更改全局变量
如前所述,如果函数内部的变量与全局变量具有相同的名称,则局部变量将屏蔽全局变量。
因此,对本地变量所做的任何更改都不会在被屏蔽时反映回全局变量。
要从函数内部修改全局变量,我们必须使用global
关键字,然后使用全局变量。
在下面的Python程序中,我们从函数内部更改全局变量的值。
# global variable x = 10 print("global variable x before function call:", x) # func def foo(): # get the global variable global x # now change the value x = 20 print("global variable x inside foo():", x) print("function call") foo() print("global variable x after function call:", x)
上面的代码将为我们提供以下输出。
global variable x before function call: 10 function call global variable x inside foo(): 20 global variable x after function call: 20