简体   繁体   中英

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. Is it because of the try/except clause? Seems like C's value would be "I will never get defined."

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. With an error, the try block can't continue, and will jump into the except block. And in the end, c haven't been defined.

Here's what happens step by step:

  • Python enters the try.. except block
  • 10 / 0 gets executed and raises a ZeroDivisionError exception
  • Python jumps to the except part of the block, skipping the c = instruction
  • print(c) gets executed, but since the definition of c was skipped, a new exception is raised

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. Before that assignment, "c" simply does not exist in the module namespace. If you print the namespace variables before the error, there is no "c". I added "foo" to demonstrate a variable that has been assigned.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM