【问题标题】:Why will the variable 'basket' not be recognised when the choices 3 or 4 are chosen?为什么选择选项 3 或 4 时无法识别变量“篮子”?
【发布时间】:2020-05-22 12:37:23
【问题描述】:
import time

shop = {'Processor': {'p3':100, 'p5':120, 'p7':200},
    'RAM':       {'16gb':75, '32gb':150},
    'Storage':   {'1tb':50, '2tb':100},
    'Screen':    {'19"':65, '23"':120},
    'Case':      {'Mini Tower':40, 'Midi Tower':70},
    'USB Ports': {'2':10, '4':20}}


basket = []







def main():
    print('''

Welcome to the PC Component Store!
Here, we sell you everything you will need.
(Keep in mind that display prices do NOT include VAT; this is added in checkout)
''')


    options()


def productchoice():

    a = 0
    ptype = ''
    pspec = ''

    print('''


We assume you have taken a look at our catalog. To add an item to your basket here, you must:


> INPUT the type of product you are looking for, e.g: "RAM"
> Then, INPUT the specification of that type of item you desire, e.g: "16gb"

> We will process your request, and OUTPUT whether it has been accepted.


> If this does not work, we will allow you to try again. If you wish to return to menu, enter "MENU" 
at each input prompt.

''')




    while a == 0:
        ptype = input('Product: ')
        pspec = input ('Specification: ')

        if ptype.lower() == 'menu' and pspec.lower() == 'menu':
            print('''Returning to menu...

''')

            options()

        elif a == 0:
            totalcost = 0
            try:
                totalcost += shop[ptype][pspec]

            except:
                print('''Your request was invalid. Please try again, and if you are unsure, return to 
menu and revisit our catalog.

''')
                continue

            else:
                addtocart(ptype,pspec)
                print(totalcost)
                print(basket)



        else:
            print('''Your request was invalid. Please try again, and if you are unsure, return to 
menu and revisit our catalog.

''')

            continue




def addtocart(ptype,pspec):
    itemstr = ptype + ' ' + pspec
    basket.append(itemstr)
    return basket



def options():

    a = 0
    while a == 0:
        choice = input('''Do you want to:
"SEE CATALOG"
"CHOOSE PRODUCT TO ADD TO BASKET"
"VIEW BASKET"
"CLEAR BASKET"

"CHECKOUT"

Enter a valid option using a number from (1-5): ''')



       if choice == '1':
        a = 1
        print('WORK IN PROGRESS')

    elif choice == '2':
        a = 1
        productchoice()

    elif choice == '3':
        a = 1
        print('Your basket contains: ')
        print(basket)


    elif choice == '4':
        a = 1
        basket = []
        print('''Basket cleared.'''
              )

        options()

    elif choice == '5':
        a = 1
        checkout()


    else:
        print('''You must select a valid option from (1-5), taking you back to the menu...
''')

        continue

main()

它出现了一个错误,说'unbourocalerror:在任命之前引用的局部变量'篮子'在选项3或4中使用'篮子'。这是什么意思?为什么在选项 2 中使用“篮子”时效果很好?我是一名进入 A-level 的 GCSE 学生,但在编码方面并不是那么出色,所以我认为 stackoverflow 可以提供帮助。这真的很令人沮丧,我需要为家庭作业做这件事。

【问题讨论】:

  • 您遇到的问题是变量范围问题。互联网上有很多关于此的文章,here is an example。原因函数options 认为basket 在分配之前被调用,是因为在elif choice == '4' 下您将basket 分配给一个空列表。这会创建一个局部变量。如果你注释掉那个赋值,你可以看到程序运行“正确”。
  • 你说得对,我刚刚重新查看了我的代码;谢谢一堆人

标签: python-3.x local-variables


【解决方案1】:

对于大多数新的 Python 开发人员来说,您面临一个非常常见的问题,那就是 变量范围问题。因此,每个变量都有自己的范围,这意味着它可以在代码中的某个点以非常特定的方式引用。您可以阅读here 了解更多信息。

就您的问题而言,您可以在函数的开头使用global 关键字。添加这一行:

global basket

在第 91 行,您的程序将完美运行。此行告诉 python 使用您在第 10 行创建的全局 basket 列表。

记住:

需要注意的是,在 python 社区中,在代码周围使用global 并不是很受欢迎,因为如果你的代码非常大并且你修改全局变量,它会导致非常复杂的代码编码。如果是这种情况,那么是时候重新构建您的代码了。

【讨论】:

  • 非常感谢这个人,它非常有帮助 - 不知道这里的人会回复这么快!
  • 新用户必须考虑到这一点,如果他们找到正确的答案并且解决了他们的问题,那么请将其标记为答案。这样如果将来有人遇到同样的问题,他们可以在不提出新问题的情况下获得方便的帮助。这就是这里的工作方式。欢迎来到 SO :)
猜你喜欢
  • 1970-01-01
  • 2011-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-10
相关资源
最近更新 更多