[英]Is the variable defined or will it raise an exception
Reading this book and am trying to understand something.阅读这本书,并试图理解一些东西。 Within this try and except clause i was told that an exception would be raised because variable C is not defined but it looks like the variable is defined.
在这个 try and except 子句中,我被告知会引发异常,因为变量 C 未定义,但看起来变量已定义。 Is it because of the try/except clause?
是因为 try/except 子句吗? Seems like C's value would be "I will never get defined."
似乎 C 的价值是“我永远不会被定义”。
try:
10 / 0
c = "I will never get defined."
except ZeroDivisionError:
print(c)
The reason c
will never be defined is because 10/0
will raise an error.永远不会定义
c
的原因是因为10/0
会引发错误。 With an error, the try block can't continue, and will jump into the except block.出现错误时,try 块无法继续,将跳转到 except 块。 And in the end,
c
haven't been defined.最后,
c
还没有被定义。
Here's what happens step by step:这是一步一步发生的事情:
try.. except
block try.. except
块10 / 0
gets executed and raises a ZeroDivisionError
exception 10 / 0
被执行并引发ZeroDivisionError
异常except
part of the block, skipping the c =
instruction except
部分,跳过c =
指令print(c)
gets executed, but since the definition of c
was skipped, a new exception is raised print(c)
被执行,但由于c
的定义被跳过,引发了一个新的异常At the module level, variables don't exist until their first assignment.在模块级别,变量在第一次赋值之前不存在。
c = "I will never get defined."
creates the variable "c" in the module's namespace and assigns the string.在模块的命名空间中创建变量“c”并分配字符串。 Before that assignment, "c" simply does not exist in the module namespace.
在分配之前,模块命名空间中根本不存在“c”。 If you print the namespace variables before the error, there is no "c".
如果在错误之前打印命名空间变量,则没有“c”。 I added "foo" to demonstrate a variable that has been assigned.
我添加了“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 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.