[英]Is the variable defined or will it raise an exception
阅读这本书,并试图理解一些东西。 在这个 try and except 子句中,我被告知会引发异常,因为变量 C 未定义,但看起来变量已定义。 是因为 try/except 子句吗? 似乎 C 的价值是“我永远不会被定义”。
try:
10 / 0
c = "I will never get defined."
except ZeroDivisionError:
print(c)
永远不会定义c
的原因是因为10/0
会引发错误。 出现错误时,try 块无法继续,将跳转到 except 块。 最后, c
还没有被定义。
这是一步一步发生的事情:
try.. except
块10 / 0
被执行并引发ZeroDivisionError
异常except
部分,跳过c =
指令print(c)
被执行,但由于c
的定义被跳过,引发了一个新的异常在模块级别,变量在第一次赋值之前不存在。
c = "I will never get defined."
在模块的命名空间中创建变量“c”并分配字符串。 在分配之前,模块命名空间中根本不存在“c”。 如果在错误之前打印命名空间变量,则没有“c”。 我添加了“foo”来演示已分配的变量。
try:
foo = "I am defined!"
print("Existing variables:", sorted(globals().keys()))
10 / 0
c = "I will never get defined."
except ZeroDivisionError:
print(c)
Output
Existing variables: ['__annotations__', '__builtins__', '__cached__', '__doc__',
'__file__', '__loader__', '__name__', '__package__',
'__spec__', 'foo']
Traceback (most recent call last):
File "m.py", line 4, in <module>
10 / 0
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "m.py", line 7, in <module>
print(c)
NameError: name 'c' is not defined
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.