试图将GLOBAL放在Python中的正确位置

问题描述 投票:0回答:1

继续得到语法错误,试图了解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 function global
1个回答
0
投票

您将路径作为参数发送,并在全局范围内声明它。 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

© www.soinside.com 2019 - 2024. All rights reserved.