Undefined Variable Nameerror In Python
Last Updated :
02 Feb, 2024
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.
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:
- When an undefined variable is used
- When there is an spelling mistake in the variable or function name
- When the variable is accessed first but defined later
- When the variable is used out of its defined scope
When Undefined Variables are Used
As already mentioned, the NameError: name 'var' is not defined signifies that the variable we are trying to access is not defined. In other words, this error occurs when the Python interpreter fails to find a variable that we are trying to access. Here is a simple example of the same that leads to the NameError: name 'var' is not defined. In the below example, we get the NameError: name 'var' is not defined simply because we are trying to access the variable 'b' when it is not even defined in the program:
Python3
a = 'GeeksforGeeks!'
print(a)
#note that we have not declared the variable b
print(b)
Output:
Traceback (most recent call last):
File "Solution.py", line 5, in <module>
print(b)
NameError: name 'b' is not defined
When there is a Spelling Mistake
Now look at the code given below. Here, we first define the variable, 'name_1' and then access it using the print statement. But still, we run into the NameError: name 'var' is not defined. Python, being a strictly typed language, treats 'name_1' and 'name_I' as two unique variables. Thus, due to this slight mistype, the Python interpreter tries to access the variable 'name_I', which naturally it is unable to find. And hence, we get the NameError: name 'name_I' is not defined.
Python3
#define the variable
name_1 = 'GeeksforGeeks!'
#access the variable
print(name_I)
Output:
Traceback (most recent call last):
File "Solution.py", line 2, in <module>
print(name_I)
NameError: name 'name_I' is not defined
A similar error will arise even if we misspell any in-built function like print() or input().
Python3
x = int(inpet("What is your age?"))
Output:
Traceback (most recent call last):
File "Solution.py", line 1, in <module>
x = int(inpet("What is your age?"))
NameError: name 'inpet' is not defined
When the Variable is Accessed First and Defined Later
In this code, the variable is declared and accessed without any error in the spelling, yet, we get the NameError: name 'var' is not defined. This happens because Python interpreter executes the code line by line. Meaning, when the print statement in the above code runs, the presence of the variable 'a' is not known by the interpreter and thus, it throws the NameError:
Python3
print(a)
a = 'GeeksforGeeks'
Output:
Traceback (most recent call last):
File "Solution.py", line 1, in <module>
print(a)
NameError: name 'a' is not defined
When a Variable is used out of its defined Scope
In the code given below, we have defined a variable inside the function demo(). But, we use the print statement outside this function to access the variable 'a'. On running this code, you will find that the code throws the NameError: name 'var' is not defined. This happens because the variable 'a' is defined inside the demo() function and hence, its scope is limited to that function only:
Python3
def demo():
a = 'GeeksforGeeks'
demo()
print(a)
Output:
Traceback (most recent call last):
File "Solution.py", line 5, in <module>
print(a)
NameError: name 'a' is not defined
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 = 'GeeksforGeeks!'
print(a)
b = 'GFG'
print(b)
Avoid Spelling Mistakes in Variable Names and Function Names
Make sure you do not misspell any variable name:
Python3
#define the variable
name_1 = 'GeeksforGeeks!'
#access the variable
print(name_1)
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 = 'GeeksforGeeks'
print(a)
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 = 'GeeksforGeeks'
print(b)
demo()
print(a)
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.
Similar Reads
__name__ (A Special variable) in Python
Since there is no main() function in Python, when the command to run a python program is given to the interpreter, the code that is at level 0 indentation is to be executed. However, before doing that, it will define a few special variables. __name__ is one such special variable. If the source file
2 min read
Unused local variable in Python
A variable defined inside a function block or a looping block loses its scope outside that block is called ad local variable to that block. A local variable cannot be accessed outside the block it is defined. Example: Python3 # simple display function def func(num): # local variable a = num print(
4 min read
Get Variable Name As String In Python
In Python, getting the name of a variable as a string is not as straightforward as it may seem, as Python itself does not provide a built-in function for this purpose. However, several clever techniques and workarounds can be used to achieve this. In this article, we will explore some simple methods
3 min read
Unused variable in for loop in Python
Prerequisite: Python For loops The for loop has a loop variable that controls the iteration. Not all the loops utilize the loop variable inside the process carried out in the loop. Example: Python3 # i,j - loop variable # loop-1 print("Using the loop variable inside :") # used loop variabl
3 min read
Variable Shadowing in Python
In this article, we will understand the concept of variable shadowing in a Python programming language. To understand this concept, we need to be well versed with the scope of a lifetime of variables in python. Local variables:When we define a function, we can create variables that are scoped only t
3 min read
Private Variables in Python
Prerequisite: Underscore in PythonIn Python, there is no existence of âPrivateâ instance variables that cannot be accessed except inside an object. However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _geek should be treated as a n
3 min read
How To Print A Variable's Name In Python
In Python, printing a variable's name can be a useful debugging technique or a way to enhance code readability. While the language itself does not provide a built-in method to directly obtain a variable's name, there are several creative ways to achieve this. In this article, we'll explore five simp
3 min read
Convert String into Variable Name in Python
There may be situations where you want to convert a string into a variable name dynamically. In this article, we'll explore how to convert a string into a variable name in Python with four simple examples. Convert String into Variable Name in PythonWhile Python does not directly allow you to convert
3 min read
Protected variable in Python
Prerequisites: Underscore ( _ ) in Python A Variable is an identifier that we assign to a memory location which is used to hold values in a computer program. Variables are named locations of storage in the program. Based on access specification, variables can be public, protected and private in a cl
2 min read
Print Single and Multiple variable in Python
In Python, printing single and multiple variables refers to displaying the values stored in one or more variables using the print() function.Let's look at ways how we can print variables in Python:Printing a Single Variable in PythonThe simplest form of output is displaying the value of a single var
2 min read