python - 我如何检查是否有全局或局部变量

标签 python function variables global local

我想检查该变量是否存在,如果存在则打印它。

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/

相关文章:

linux - 我可以在 bash 中设置特定数字而不是序列吗?

Jquery,变量未定义

python - 多索引 Pandas 数据框子集分配

Python 从单个标签解析 XML 变量

javascript - 调用 value + style.display 函数?

function - D 如何通过返回类型解决这个问题?

python - django中是否有类似于 'rake routes'的东西?

python - 使用scipy.optimize时如何处理 'residues are not finite in the initial point'?

c++ - 调用同名函数

ios - 在 xcode 中传递变量返回 null