【发布时间】: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