这个问题已经有了答案:
我正在处理一个项目,并在运行脚本时不断得到变量未定义错误。如何在不声明全局变量的情况下解决此问题
def func1(): x = 1 def func2(): y=5 x + y = z print(z)
x 在本地范围内 func1 ,因此无法从中读取 func2 . 你可以使用 global x = 1 但我不推荐。反而通过 X 到 函数2 :
x
func1
func2
global x = 1
X
函数2
def func1(): x = 1 return x def func2(x): y = 5 z = x + y # You had this backwards as well (i.e. x + y = z) print(z) x = func1() func2(x)