Why do I Get a NameError Instead of a SyntaxErorr Here?


#1

The exercise mentions that the above code will result in a NameError, instead it results in a syntax error, why?


FAQ: Learn Python - Python Syntax - Handling Errors
#2

Hi @vineet_95,

A NameError is caused by trying to work with a variable that doesn’t exist. It’s only when you print multiple words without quotes that the interpreter gives a SyntaxError instead. See this example:

>>> print(foo)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
>>> print(foo bar)
  File "<stdin>", line 1
    print(foo bar)
                ^
SyntaxError: invalid syntax

I don’t know for sure, but I’d guess the reason it gives a SyntaxError in the second example is because the interpreter reads the arguments passed to print(), then looks up each variable to get its value. Since the arguments are passed incorrectly (without a comma separating them), it errors out right there without proceeding to look up the variables and realize they don’t exist (which causes a NameError).

Even if the two variables are defined, the same error message is produced as before, due to the missing comma:

>>> foo = "test"
>>> bar = "hello"
>>> print(foo bar)
  File "<stdin>", line 1
    print(foo bar)
                ^
SyntaxError: invalid syntax

Try putting commas between each word, and you’ll get a NameError instead of a SyntaxError:

>>> print(foo, bar)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined

Hope this helps!