【问题标题】:python: multiply an input by a number in a dictpython:将输入乘以dict中的数字
【发布时间】:2016-10-27 14:33:29
【问题描述】:

我正在尝试通过预制字典中的另一部分代码来对用户给定的号码进行复数。这是我的示例代码

randomdict = {'22' : {'name' : 'sponge', 'price' : 1}}
choice = input("Enter a number: ")
amount = input("How much of that item?: ")
if choice in randomdict:
    price  = amount * (randomdict['price'])
    print("Price is "+str(price))

如您所见,我正在尝试获取用户输入的金额乘以保存在字典 randomdict 中的商品价格。我该怎么做呢?试了好几次都搞不定

【问题讨论】:

  • 选择和金额是字符串。您需要先将它们解析为数字。
  • 如果我这样做,那么price = amount * (randomdict['price']) 行是否正确?
  • 一旦等式中的所有内容都是数字,是的,它应该可以工作。

标签: python dictionary input


【解决方案1】:

randomdict['price'] 不存在。你要randomdict[choice]['price']

此外,如果您想计算价格,您希望 amount 为整数。

price  = int(amount) * randomdict[choice]['price']

附带说明:price 可能不是该值的最佳名称。这个值实际上是 total(价格 x 数量)而不是 price。明确地写出来:

quantity = int(amount)
price = randomdict[choice]['price']
total = price * quantity

【讨论】:

    【解决方案2】:

    第一行的'22' 是干什么用的?你有一本字典里面的字典,价格在里面的字典里面。 你的输入必须是'22',所以你会选择'22',你必须查看的字典是randomdict[choice]。要得到你需要的价格randomdict[choice]['price']

    if choice in randomdict:
        price  = amount * (randomdict[choice]['price'])
        print("Price is "+str(price))
    

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      我会使用两步程序。 如果在 randomdict 中选择: z=随机[选择] p=z['价格'] 价格=int(金额)*p

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-23
        • 2022-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多