首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Python3循环中增加一个在每次重启时改变其值的变量列表?

如何在Python3循环中增加一个在每次重启时改变其值的变量列表?
EN

Stack Overflow用户
提问于 2018-06-29 04:15:12
回答 1查看 16关注 0票数 0

我有个问题。我想做一个购物清单,询问用户它想要什么商品,有多少。该列表将在每次循环“重新启动”时通过添加项目的名称(一个字符串)和与其关联的数字(一个整数)而演变。唯一的问题是,当循环“重新启动”时,列表的内容会被重置。

代码如下:

代码语言:javascript
复制
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.

但是,在控制台上,我有以下内容:

代码语言:javascript
复制
TypeError: unsupported operand type(s) for +=: 'dict' and 'tuple'

我找不到不重置客户之前说的话的方法...

附言:对不起,我的英语,我是法国人…:)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-29 04:29:17

下面的函数将返回用户想要购买的项目的字典,以达到他们想要的每个项目的数量。

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51090616

复制
相关文章

相似问题

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