Brainlag
  1. Library
  2. Debugging
  3. Python

NameErrorWhat is a NameError?

Python stops with a NameError when a line uses a name it has never been given. Usually a typo, a wrong capital, or the right name used too early.

Python5 min

What Python is telling you

Output
NameError: name 'scroe' is not defined

Python reads the message as: "this line uses scroe, and nothing called scroe exists yet". It only knows names that an earlier line created with =, def, for or import.

The three usual reasons:

  • A typo. scroe instead of score. Compare the two spellings letter by letter.
  • A capital letter. Score and score are different names.
  • Used too early. The name is created further down, so it does not exist yet when this line runs.

How to find it

Read the last line of the error first: it names the culprit. The line number above it says where it was used. Then search your code for where that name is created. If it is created nowhere, or below that line, you have found the bug.

Run it: one letter off

Press Run and read the error from the bottom up.

main.py to run
coins = 40
bonus = 15
total = coins + bonnus
print(total)

The level that does not exist

This should print Level 4 reached. Run it, read the error, then fix it.

exercise_1.py to run
level = 3
Level = level + 1
print("Level", levell, "reached")

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.