1

I have 2 scenarios where the verdict results into a runtime error, but with 2 different messages:

Scenario 1:

def a():
    print(aa+bb)
    #aa=10
    #bb=20
    
print(a())

Verdict for Scenario 1:

Traceback (most recent call last):
File "Solution.py", line 6, in <module>
    print(a())
File "Solution.py", line 2, in a
    print(aa+bb)
NameError: name 'aa' is not defined

Scenario 2:

def a():
    print(aa+bb)
    aa=10
    bb=20
    
print(a())

Verdict for Scenario 2:

Traceback (most recent call last):
File "Solution.py", line 6, in <module>
    print(a())
File "Solution.py", line 2, in a
    print(aa+bb)
UnboundLocalError: local variable 'aa' referenced before assignment

Now, if the interpreter executes the code line by line and immediately halted after it encountered an error on line 2, how did it generated 2 different error messages.

Deepak Tatyaji Ahire
  • 4,883
  • 2
  • 13
  • 35
  • The error message is a traceback report. The specific error occurred on line 6 in the print(aa+bb) call, the source of this error was the statement on line 6 which asks to print the return of a(). By the way, your function has ne return so the result of this call will produce a None. – itprorh66 Dec 09 '20 at 13:56
  • This is a great question, but ultimately a duplicate. I'll find the duplicate momentarily. Short answer: CPython sticks assignments made locally into a table as a compilation step. The first case has no assignments, the second one does. Nice job making an MCVE. – Mad Physicist Dec 09 '20 at 13:57
  • @itprorh66. You're stating the absolute obvious and completely ignoring the question. – Mad Physicist Dec 09 '20 at 13:58
  • Cool @MadPhysicist, waiting for your comment. – Deepak Tatyaji Ahire Dec 09 '20 at 13:58
  • Could you add a plain python tag please? – Mad Physicist Dec 09 '20 at 14:01
  • Added @MadPhysicist. – Deepak Tatyaji Ahire Dec 09 '20 at 14:01
  • @MadPhysicist Obviously, I am not either clearly answering the question or you are ignoring the obvious. The question states, if the interpreter executes code line one by one, and immediately halts when an error is encountered how does it generate two error messages. The answer is it doesn't generate two messages, it generates 1 message, the fact that local variable aa is referenced before it is assigned, the error report then backs up the stack to identify the place where the offending error was originated from. – itprorh66 Dec 09 '20 at 15:20
  • @itprorh66. I think you're misreading the question. As far as I can tell, it's asking why you get different exceptions under different circumstances. I don't think anyone disagrees that you can only get one exception per run. I think we're basically on the same page. – Mad Physicist Dec 09 '20 at 15:39
  • @MadPhysicist, Oh my bad! – itprorh66 Dec 09 '20 at 15:45
  • Python is **not** an interpreted language. – Karl Knechtel Sep 09 '22 at 12:24

0 Answers0