Within a Python program, everything is spelled correctly, but I still receive a
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 as two completely different variables, despite them having the same spelling because the casing of each letter is not the same.
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
print(year) year = "2018" # A NameError will be thrown because year is not yet defined # when the first line of code runs.