Editor

NameError: name 'username' is not defined

What it means

Python met a name it does not know. Either the name was never created, it is spelled differently from where you created it, or it is used before the line that creates it. Python 3.13 often adds Did you mean: ...? with the closest name it knows.

1. A typo in the name

This raises the error

Broken
user_name = "Ada"
print("Welcome back,", username)
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
NameError: name 'username' is not defined. Did you mean: 'user_name'?

The fix

Fixed
user_name = "Ada"
print("Welcome back,", user_name)
Output
Welcome back, Ada

Names must match exactly, including underscores and capital letters. username, user_name and User_name are three different names.

Try fixing it yourself in the editor

2. Using a variable before the line that creates it

This raises the error

Broken
price = 20
print("Total:", price * quantity)
quantity = 3
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
NameError: name 'quantity' is not defined

The fix

Fixed
price = 20
quantity = 3
print("Total:", price * quantity)
Output
Total: 60

Python runs your code from top to bottom. A variable exists only after the line that assigns it has run.

Try fixing it yourself in the editor

3. Text without quotes around it

This raises the error

Broken
name = Ada
print("Hello,", name)
Output
Traceback (most recent call last):
  File "<exec>", line 1, in <module>
NameError: name 'Ada' is not defined

The fix

Fixed
name = "Ada"
print("Hello,", name)
Output
Hello, Ada

Without quotes, Python reads Ada as the name of a variable and looks for it. Quotes make it text.

Try fixing it yourself in the editor

When you see this error, check

  • Read the Did you mean hint at the end of the message: it is usually right.
  • Check spelling and capital letters against the line where you created the name.
  • Make sure the line that creates the variable runs before the line that uses it, and is not skipped by an if.
  • A variable created inside a function exists only inside it. return it to use it outside.
  • For a module such as math, add import math at the top. Python then hints Did you forget to import 'math'?.

All Python errors · How to read a traceback · Step through your code