我想检查该变量是否存在,如果存在则打印它。
x = 10
def example():
z = 5
print("X (Global variable) : ",x)
print("Z (example() : ",z)
example()
print(z)
当我添加 print(z)
时,它显然会引发错误,因为没有名为 z 的变量。
谢谢大家的回答。 (特别是 Jasper、kevin 和 icantcode)
x = 10
def example():
z = 5
example()
try:
print(z)
except NameError:
print("There is no global variable called Z! ")
最佳答案
内置方法 locals()
和 globals()
返回本地/全局变量名称及其值的字典。
if 'z' in locals():
print(z)
关于python - 我如何检查是否有全局或局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37512712/