首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在此场景中使用global?

如何在此场景中使用global?
EN

Stack Overflow用户
提问于 2019-12-03 11:48:36
回答 2查看 60关注 0票数 1

我是个编程新手,我真的不明白如何使用很多这样的代码。如果有人告诉我在这种情况下如何使用global,会对我有很大的帮助。

代码语言:javascript
复制
def tshirtadd():
    global perch
    perch = 0
    print("you have",perch,"T-shirts")
    add = int(input("how many t-shirts would you like to add? "))
    perch+add
    return perch


def tshirtremove():
    global perch
    print("You have",perch,"Tshirts")
    remove = int(input("How many Tshirts would you like to remove? "))

    perch - remove

    return perch


def order():
    global perch
    print(perch)
    print(perch*10)
    return main


def main():
    ordering = int(input("Would you like to add,remove, view order, or purchase?"))
    print(list1)
    count = 0
    for x in list1:
        count = count+1
        print(count,"\b)",x)
    perch = 0

    if ordering == 1:
        tshirtadd()
        print("you have",perch,"Tshirts")
        return main()
    elif ordering == 2:
        tshirtremove()
        return main()
    elif ordering == 3:
        order()
        return main()
    else:
        exit
    print(perch)
main()
EN

回答 2

Stack Overflow用户

发布于 2019-12-03 12:09:18

您应该在使用global之前初始化变量perch,perch = 0应该在函数定义之前的顶部。

我认为您正在尝试初始化主函数中的perch,但这不是全局函数的工作方式,您需要在所有函数之前在外部定义它,并且您可以像其他函数一样在main()中使用全局perch,如果需要,可以在那里将其设置为零

票数 0
EN

Stack Overflow用户

发布于 2019-12-03 12:28:41

回答你的问题:当我们想要从任何地方访问我们的变量时,我们通常使用global。所以你只需要定义一次global variable,你就可以在任何地方使用它。

我对你的代码做了一些修改。(需要更多更改,但不确定这段代码真正想要实现的是什么)

这可能会帮助您理解global的概念

代码语言:javascript
复制
def tshirtadd():

        print("you have",perch,"T-shirts")
        add = int(input("how many t-shirts would you like to add? "))
        perch += add
        return perch


    def tshirtremove():
        print("You have",perch,"Tshirts")
        remove = int(input("How many Tshirts would you like to remove? "))

        perch -= remove

        return perch


    def order():
        print(perch)
        print(perch*10)
        return main


    def main():
        global perch
        perch = 0
        ordering = int(input("Would you like to add,remove, view order, or purchase?"))
        print(list1)
        count = 0
        for x in list1:
            count = count+1
            print(count,"\b)",x)
        perch = 0

        if ordering == 1:
            tshirtadd()
            print("you have",perch,"Tshirts")
            return main()
        elif ordering == 2:
            tshirtremove()
            return main()
        elif ordering == 3:
            order()
            return main()
        else:
            exit
        print(perch)
    main()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59149928

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档