How to Solve an Undefined Variable NameError in Python?

To solve the NameError: name ‘var’ is not defined, you should take care of the pointers mentioned above. The previous examples can be updated to get rid of the error as follows:

Define the Variable before using it

Make sure to define a variable before you use it:

Python3




a = 'w3wiki!'
print(a)
  
b = 'GFG'
print(b)


Output

w3wiki!
GFG


Avoid Spelling Mistakes in Variable Names and Function Names

Make sure you do not misspell any variable name:

Python3




#define the variable
name_1 = 'w3wiki!'
 
#access the variable
print(name_1)


Output

w3wiki!


Make sure you do not misspell any in-built function or user-defined function:

Python3




x = int(input("What is your age?"))
print(x)


Output:

What is your age?20
20

Access a Variable only when its first defined

Make sure you first create the variable and then use it and not the other way around:

Python3




a = 'w3wiki'
print(a)


Output

w3wiki


Access the Variable in its defined scope

Make sure you do not access a variable out of its defined scope.

Python3




a = 'GFG'
def demo():
  b = 'w3wiki'
  print(b)
   
demo()
print(a)


Output

w3wiki
GFG


Apart from taking care of all these pointers, you can also setup the try-else block to resolve this error in a more efficient manner. Read all about it here – Handling NameError Exception in Python.

Conclusion

In this post, we looked at the different reasons that might lead to an undefined variable nameerror in Python. Although in most cases this error is thrown because of a wrong spelling, the use of scope is also often overlooked, which naturally leads to the nameerror. Although avoiding this error is the best that you can do, especially now that you are aware of the scenarios that lead to it, exploring the use of exception handling is also a great option to save you from this error for once and for all.



Undefined Variable Nameerror In Python

Encountering the “NameError: name ‘var’ is not defined” is a common experience for Python users. In Python, variable declaration is a straightforward process of assigning a value. This error arises when attempting to access a non-existent variable or one not defined in the program. Surprisingly, it can occur even when the variable is present, owing to various reasons. In this discussion, we explore the nuances of the NameError and strategies to resolve this issue in Python programming.

Similar Reads

Why Does the Python NameError: name ‘var’ is not defined Arise?

Various reasons might lead to the Python NameError: name ‘var’ is not defined. Let us have a look at these common reasons:...

How to Solve an Undefined Variable NameError in Python?

...

Contact Us