我有个问题。我想做一个购物清单,询问用户它想要什么商品,有多少。该列表将在每次循环“重新启动”时通过添加项目的名称(一个字符串)和与其关联的数字(一个整数)而演变。唯一的问题是,当循环“重新启动”时,列表的内容会被重置。
代码如下:
def shopping(n):
x=0
while x<n:
item={}
nb={}
shopping_cart={}
item[x]=str(input("item?")) #We asking the user the name of the item he wants.
nb[x]=int(input("nb?")) #We asking the user the number he wants.
shopping_cart[x] = item[x],nb[x]
shopping_cart+=shopping_cart[x] #We try to add what the user has entered to a dictionary to not reset what he has entered before.
x+=1
print(shopping_cart)
shopping(2) #To simplify, in this exemple, we imagine that the customer want to buy two differents items.
但是,在控制台上,我有以下内容:
TypeError: unsupported operand type(s) for +=: 'dict' and 'tuple'
我找不到不重置客户之前说的话的方法...
附言:对不起,我的英语,我是法国人…:)
发布于 2018-06-29 04:29:17
下面的函数将返回用户想要购买的项目的字典,以达到他们想要的每个项目的数量。
def shopping(n):
cart = {}
for _ in range(n):
item = input("What would you like to buy?")
amount = int(input("How many would you like?"))
cart[item] = cart.get(item, 0) + amount
return cart
https://stackoverflow.com/questions/51090616
复制相似问题