请继续获取语法错误,尝试了解GLOBAL在Python函数中的位置和工作方式。
import os
path = "start"
route = "1"
def pathcontrol(route, path):
global path
while path=="start":
if route == "1":
path = "one"
elif route == "2":
path = "two"
else:
return
pathcontrol(route, path)
print("Exit Path = "+path)
exit=input("Press enter to exit ")
想法是也为“ route”添加一个input(),以便用户可以选择1或2,但是我知道如何进行管理。
谢谢, :-)
答案 0 :(得分:0)
您正在将path in作为参数发送,并在全局进行声明。 Python现在不知道要使用哪个path
变量:全局变量还是参数。
也:global
关键字被认为是不良做法。参见例如皮林特W0603。
无论如何,知道如何工作真是一件好事。以下将打印exit path=one
因为您正在访问和编辑实际的全局path
变量。
import os
path = "start"
route = "1"
def pathcontrol(route):
global path
while path=="start":
if route == "1":
path = "one"
elif route == "2":
path = "two"
else:
return
pathcontrol(route)
print("Exit Path = "+path)
但是,在下面的示例中,您正在访问path
,但没有对其进行编辑。您正在“复制”全局范围内的一个:
import os
path = "start"
route = "1"
def pathcontrol(route, path):
while path=="start":
if route == "1":
path = "one"
elif route == "2":
path = "two"
else:
return
pathcontrol(route, path)
print("Exit Path = "+path)
这将打印exit path=start