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! ")
The built-in methods locals() and globals() return a dictionary of local/global variable names and their values.
if 'z' in locals():
print(z)
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()
But this could potentially fail because something_with doesn't exist or has a typo/bug in it so the NameError you catch may be unrelated to the z variable.
you could also check dictionaries of locals() and globals() (and builtins module if you want to go that deep)
# import builtins
if 'z' in locals() or 'z' in globals(): # or hasattr(builtins, 'z'):
print(z)
else:
fallback_code()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With