bonum77 bonum77 - 6 months ago 11
Python Question

How can i check if there is a global or local variable

I want to check if that variable exists and print it if it does.

x = 10

def example():

z = 5

print("X (Global variable) : ",x)
print("Z (example() : ",z)

example()

print(z)


When i add
print(z)
it will obviously raises an error because there is no variable called z.

Thanks for the answers guys. (specially Jasper, kevin and icantcode)

x = 10
def example():

z = 5

example()


try:
print(z)
except NameError:
print("There is no global variable called Z! ")

Answer

The most straight forward way would be to try to use it and if it fails do something else:

try:
    something_with(z)
except NameError:
    fallback_code()

you could also check dictionaries of locals() and globals()

if 'z' in locals() or 'z' in globals():
    print(z)
else:
    fallback_code()