What causes a NameError?

Question

What are the common causes of a NameError, and how can I fix it?

Answer

One of the most common reasons why you may see a NameError is if you are trying to use a variable that hasn’t been assigned a value yet. For example, the following code will produce a NameError because we are trying to reference the value of tax on line 2, but tax isn’t assigned a value until line 3:

price = 20
total_cost = price + tax
tax = 0.15 * price

We can fix this by changing the order of the lines:

price = 20
tax = 0.15 * price
total_cost = price + tax

Another common cause of a NameError is a typo in the variable name. For example, in the following code, num is misspelled as nmu, which would be treated as a new variable that has not yet been assigned a value:

num = 3
half_num = nmu / 2

This can easily be fixed by correcting the typo:

half_num = num / 2
1 Like