I spelled everything correctly, but still receive a NameError. Why?

Question

Within a Python program, everything is spelled correctly, but I still receive a NameError. Why?

Answer

There are some possible reasons that a NameError can appear even if everything is spelled correctly in the code.

Reason 1: Inconsistent casing

One common reason is due to inconsistent casing of any variable names or functions. For example, Python will view Name and name as two completely different variables, despite them having the same spelling because the casing of each letter is not the same.

Code example

name = "Monty"
print(Name)
# This will output a NameError because 
# the casing is not consistent.

Print("Hi!")
# This will output a NameError because 'Print' is not defined.

Reason 2: Ordering of the code

Another common reason is due to code ordering. The variable was used on a code line earlier than the code line where it was defined. Python generally processes the code from top to bottom, so if it encounters a variable not yet defined, it would throw a NameError.

Code example

print(year)
year = "2018"
# A NameError will be thrown because year is not yet defined 
# when the first line of code runs.
31 Likes

Hello
The example presented during the lecture didn’t throw any NameError before SyntaxError has been cleared.
I would like to know why it doesn’t display both SyntaxError and NameErrors at the same time.
please reply.
Thank you.

7 Likes

Syntax is checked in the parsing stage, pre-compile, so those errors are raised before the code is even run. NameError is a runtime exception that will only be encountered when the code is being executed, post-compile.

19 Likes

Hello Roy
Your face reminds me an old friend in virginia.
Thank u for all those comments

5 Likes

Hi friend.

Regarding your response there are some concepts I m lost. Can you please explain in simple words the following:

  • parsing :
  • pre-compile :
  • post-compile :
  • runtime exception :

Regards.

Parsing is the analyzing of text for keywords, arguments, data, &c. It is the interpretive phase.

Pre-compile is when the parsed code is translated into byte code. I believe in Python this is the form it takes before it is given over to the compiler to put into machine language.

Post-compile is the executable machine code.

Runtime exception is any error that occurs during runtime. It is usually data related but could be due to errant logic or some other issue such as out of memory, etc. These are fatal errors that cease program operation in its tracks.

2 Likes