Undefined variable NameError

import traceback, sys

number1 = 100
number2 = 2

print('start')
try:
    answer = number1 / number2
    print(answer2)
except NameError as e:
    print('Calling an undefined variable')
    sys.stderr.write(traceback.format_exc())
finally:
    print('end')

Execution result


start
Calling an undefined variable
end

Run-time error


Traceback (most recent call last):
  File "Main.py", line 9, in <module>
    print(answer2)
NameError: name 'answer2' is not defined

Originally in the scene where answer is printed out I have called an undefined variable called answer2.

Exclude the target of the error From the case of an error divided by 0 Change from ZeroDivisionError to NameError I just changed the output string to'calling an undefined variable'.

Recommended Posts

Undefined variable NameError
Variable scope