Name Errors
A NameError means Python tried to use a name that does not exist in the
current scope.
Python knows score. It does not know scores.
This is one of the most useful early errors because it usually points to a small problem:
- a typo;
- a name used before assignment;
- a name created only inside a branch that did not run;
- a local name used outside its function.
Typo in a name
The fix is not conceptual. It is spelling:
Used before assignment
Python runs top to bottom:
The assignment happens too late. Move the assignment before the use.
Created only in one branch
If the condition is false, label is never created.
A clearer version assigns a value in every path:
A branch can skip a name
Ready to run.
Local names stay local
Names created inside a function belong to that call:
The name label inside the function is not available outside. Use the return
value:
This code fails:
Which name did Python fail to find?
Answer it first, then check.
HintInspect the use site
Read the name between the parentheses in print(...).
Solutionitem is missing
The program defines items, plural, but tries to print item, singular.
Since item was never assigned, Python raises NameError for that name.