Skip to main content

How to Fix “NameError: name is not defined” in Python

Have you ever run into a problem where you get a “NameError: name ‘variable_name’ is not defined” error in Python? If so, you’re not alone.

First, check to make sure that the variable_name variable is actually defined. It’s possible that you simply forgot to include it in your code. If that’s the case, all you need to do is to define the variable_name.

print(sheets) #this code return errors because you haeven't defined the sheets variable yet

#define the variable sheets then use it
sheets = [
    {'label': 'Trade Receivable Account', 'items': []},
    {'label': 'Trade Payable Account', 'items': []},
    {'label': 'GST Payable', 'items': []},
]
print(sheets)

Other than that, there are a few other potential causes of this error. For example, it’s possible that you’re using an older version of Python. In Python 3, the print() function was changed to a built-in function, which means that it doesn’t need to be surrounded by parentheses. However, in Python 2, the print statement does need parentheses. So, if you’re using Python 2 and you forget to include them, you’ll get this error. 

By continuing to use the site, you agree to the use of cookies.