Code with the error

price = 40
print(price * quantity)

Error message (Python 3.12, last line)

NameError: name 'quantity' is not defined

Corrected code

price = 40
quantity = 3
print(price * quantity)

Output

120

Common causes

  • The variable is used before it gets a value.
  • A typo or different letter case: Total and total are two names.
  • Text without quotes: print(hello) looks for a variable called hello.
  • A variable created inside a function is used outside it.

Practise in the course

Lesson: Variables

Frequently asked questions

Why do I get NameError for ordinary text?

Without quotes Python treats a word as a name. Write the text in quotes: "hello".

Does letter case matter in names?

Yes. age, Age and AGE are three different names.