python 无法调用全局变量
python cant call a global variable
编辑:问题解决了为什么你还在给负分
我创建了一个这样的函数:
def testFunc():
global testVar
if True:
testVar = input("input something: ")
def anotherFunc():
if testVar == "test":
print("okay")
anotherFunc() #calling function
但是我收到一个错误:
File "C:/Users/jeffpc/Desktop/Files/wqw.py", line 8, in anotherFunc
if testVar == "test":
NameError: name 'testVar' is not defined
这里有什么问题?
语句 global testVar
根本没有按照您的代码片段执行。您需要在 testFunc()
之外声明全局变量或在调用 anotherFunc()
之前调用它
对于您的代码,下面是正确的解决方案,因为 testVar
不仅已初始化,而且还在 testFunc()
中赋值
def testFunc():
global testVar
if True:
testVar = input("input something: ")
def anotherFunc():
if testVar == "test":
print("okay")
testFunc()
anotherFunc()
编辑:问题解决了为什么你还在给负分
我创建了一个这样的函数:
def testFunc():
global testVar
if True:
testVar = input("input something: ")
def anotherFunc():
if testVar == "test":
print("okay")
anotherFunc() #calling function
但是我收到一个错误:
File "C:/Users/jeffpc/Desktop/Files/wqw.py", line 8, in anotherFunc
if testVar == "test":
NameError: name 'testVar' is not defined
这里有什么问题?
语句 global testVar
根本没有按照您的代码片段执行。您需要在 testFunc()
之外声明全局变量或在调用 anotherFunc()
对于您的代码,下面是正确的解决方案,因为 testVar
不仅已初始化,而且还在 testFunc()
def testFunc():
global testVar
if True:
testVar = input("input something: ")
def anotherFunc():
if testVar == "test":
print("okay")
testFunc()
anotherFunc()