名称错误:未定义名称 "useraction"。

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

我确保在main()之前有全局,而且我确实给变量useraction赋了一个值。为什么它仍然说它是未定义的?

    import os.path
    from os import path     

    shoppinglist = []   
    global useraction   

    def main():
        Displaylist()     
        RunItemAction()   


    def Displaylist():
        i = 0
        if (len(shoppinglist)>0):
    while (i<=len(shoppinglist)):
        print(shoppinglist[i] +"\n")
        i+=1

        useraction = str(input("Do you want to add, remove, or search for an item? "))
        useraction = useraction.upper()

    def RunItemAction():
        if( useraction == "ADD"):     
            AddItem()
python global-variables undefined
1个回答
0
投票

我认为你应该这样使用它。

    import os.path
    from os import path     

    shoppinglist = []   
    useraction=""  # or any default value you want to give   

    def main():
        Displaylist()     
        RunItemAction()   


    def Displaylist():
        global useraction
        i = 0
        if (len(shoppinglist)>0):
            while (i<=len(shoppinglist)):
                print(shoppinglist[i] +"\n")
                i+=1

        useraction = str(input("Do you want to add, remove, or search for an item? "))
        useraction = useraction.upper()

    def RunItemAction():
        global useraction
        if( useraction == "ADD"):     
            AddItem()

0
投票

任何在全局作用域定义的名称,根据定义,都是全局的。

在全局范围内定义的任何名称,根据定义,都是全局的。global 语句用于 另一个 的作用域来标记一个原本是本地的名称为全局的。

import os.path
from os import path     

shoppinglist = []   

def main():
    Displaylist()     
    RunItemAction()   


def Displaylist():
    global useraction
    i = 0
    if (len(shoppinglist)>0):
        while (i<=len(shoppinglist)):
            print(shoppinglist[i] +"\n")
            i+=1

    useraction = str(input("Do you want to add, remove, or search for an item? "))
    useraction = useraction.upper()

def RunItemAction():
    global useraction
    if( useraction == "ADD"):     
        AddItem()

也就是说,根本就不要使用全局变量。将参数传递给函数,并让它们返回值。

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