简体   繁体   中英

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! ")

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()

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

if 'z' in locals() or 'z' in globals():
    print(z)
else:
    fallback_code()
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM