继续得到语法错误,试图了解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,但我知道如何管理它。
谢谢, :-)
您将路径作为参数发送,并在全局范围内声明它。 Python现在不知道使用哪个path
变量:全局变量或参数。
另外:global
关键字被认为是不好的做法。参见例如Pylint W0603。
无论如何,知道如何工作是一件好事。以下将打印exit path=one
,因为您正在访问和编辑acttual全局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