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


#1

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.