Reputation:
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! ")
Upvotes: 4
Views: 13141
Reputation: 21464
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()
Upvotes: 4
Reputation: 33
try:
print(z)
except NameError:
print("No variable named z!")
This code try's to print z and if there is no variable named z, it will run the code under except.
Upvotes: -1
Reputation: 9008
The built-in methods locals()
and globals()
return a dictionary of local/global variable names and their values.
if 'z' in locals():
print(z)
Upvotes: 6