![](/img/trans.png)
[英]Why does Python let you instantiate local variables as global from inside a function?
[英]Why does Python let me use variables assigned in a nested block without the "global" keyword?
为什么即使我没有在全局范围内定义userInput
变量,这个程序也能运行?
intInput = True
while intInput == True:
try:
userInput = int(input())
intInput = False
except ValueError:
print('You must enter an integer.')
print(userInput) # shouldn't this fail, since userInput was defined in a block?
您的代码有效,因为 python 没有block scopes
。 您可以在此线程上了解更多信息: Python 中的块作用域
如果您在 while 语句中定义变量,则与在全局范围内定义变量(在您的情况下)是一样的。
intInput = True
while intInput == True:
try:
# userInput here is global, because it's inside a while statement only
userInput = int(input())
intInput = False
except ValueError:
print('You must enter an integer.')
print(userInput)
基本上,在“块范围”内声明的变量将从声明它的地方开始。
例如,如果您的代码在函数内部,则userInput
变量将具有函数的范围,然后,您的代码将生成错误:
intInput = True
def do_your_thing():
while intInput == True:
try:
# userInput being declared here will have the function's scope
userInput = int(input())
intInput = False
except ValueError:
print('You must enter an integer.')
# you are trying to access userInput outside its scope
print(userInput)
现在,如果您尝试运行此代码,您将看到错误:
Traceback (most recent call last):
File "teste.py", line 28, in <module>
print(userInput)
NameError: name 'userInput' is not defined
在 Python 中,您不需要在全局范围内定义变量。 在你放置var_name = value
的任何地方你都有一个新变量。
如果你想声明一个全局变量,然后在函数或类范围内使用它,你应该像这样使用global
关键字:
test = 123
def func()
global a
print(a) # 123
您拥有的代码没问题,并且您确实在全局范围内定义了它,因为您放入了一个循环而不是一个函数。 如果您在函数中定义它,那么它会给您一个错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.