Today, we will see how to check if a variable exists or not. In Python, a variable can be defined either globally or locally.
If a variable is defined inside a function, then it has a local scope. Otherwise (defined outside any function), it has a global scope. Let’s see how to check their existence one by one.
Existence of a local variable
We will use the locals() method to see if a variable exists locally. The locals() method returns a dictionary of the current scope’s local variables. Let’s take an example.
summ=4 def test(c): a = 3 b = 4 result = a + b + c if 'result' in locals(): print("The result variable exists in the local scope. Value is:", result) else: print("Sorry, the variable does not exist in the local scope.") if 'summ' in locals(): print("The summ variable exists in the local scope. Value is:", summ) else: print("Sorry, the variable does not exist in the local scope.") test(4)
The result variable exists in the local scope. Value is: 11 Sorry, the variable does not exist in the local scope.
In the above example, we create a test() function. It calculates the sum of three values and stores it in the result variable.
Then, it checks if result exists in the local scope or not. Since it does, the condition gets evaluated to True and the statement in the if block runs.
The summ variable, on the other hand, is not local. Therefore, its if-condition gets evaluated to False.
Existence of a global variable
To check if a global variable exists, we will use the globals() method. It returns a dictionary containing the current scope’s global variables. Let’s take an example.
summ=4 def test(c): a = 3 b = 4 result = a + b + c if 'result' in globals(): print("The result variable exists in the local scope. Value is:", result) else: print("Sorry, the variable does not exist in the local scope.") if 'summ' in globals(): print("The summ variable exists in the local scope. Value is:", summ) else: print("Sorry, the variable does not exist in the local scope.") test(4)
Output
Sorry, the variable does not exist in the local scope. The summ variable exists in the local scope. Value is: 4
This is the same example as above, except we check for the global scope. Since summ is a global variable, its value gets displayed, and result is a local variable, its condition gets evaluated to False.
Hey guys! It’s me, Marcel, aka Maschi. On MaschiTuts, it’s all about tutorials! No matter the topic of the article, the goal always remains the same: Providing you guys with the most in-depth and helpful tutorials!