[英]Why does Python let me use variables assigned in a nested block without the "global" keyword?
Why does this program work even if I do not define the userInput
variable in the global scope?为什么即使我没有在全局范围内定义
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?
Your code works because python don't have block scopes
.您的代码有效,因为 python 没有
block scopes
。 You can learn more about it on this thread: Block scope in Python您可以在此线程上了解更多信息: Python 中的块作用域
If you define your variable inside a while statement, it's the same thing as defining your variable at the global scope (in your case).如果您在 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)
Basically, the variable declared inside a "block scope" , will have its scope from where it is being declared.基本上,在“块范围”内声明的变量将从声明它的地方开始。
For example, if your code was inside a function, then the userInput
variable would have the function's scope, and then, your code would generate an error:例如,如果您的代码在函数内部,则
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)
Now, if you try to run this code, you'll see the error:现在,如果您尝试运行此代码,您将看到错误:
Traceback (most recent call last):
File "teste.py", line 28, in <module>
print(userInput)
NameError: name 'userInput' is not defined
In Python you don't need to define the variables in the global scope.在 Python 中,您不需要在全局范围内定义变量。 Everywhere you put
var_name = value
you have a new variable.在你放置
var_name = value
的任何地方你都有一个新变量。
If you want to declare a global variable and then use it in function or class scope you should use the global
keyword like this:如果你想声明一个全局变量,然后在函数或类范围内使用它,你应该像这样使用
global
关键字:
test = 123
def func()
global a
print(a) # 123
The code you have is ok and you did define it globally since you put in in a loop instead of a function.您拥有的代码没问题,并且您确实在全局范围内定义了它,因为您放入了一个循环而不是一个函数。 If you defined it in a function then it would give you an error.
如果您在函数中定义它,那么它会给您一个错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.