首页 > 解决方案 > 如何在 Python 中从多个用户输入中获取多个输出(无效文字错误)

问题描述

这是一个非常简单的代码:

walmart_prices = [0, 10, 15, 20, 12, 25]
costco_prices = [0, 5, 20, 15, 10, 12]
sprouts_prices = [0, 12, 8, 15, 20, 18]

store = input("Walmart, Costco, or Sprouts?").lower()

if store == ("walmart"):
    w_items = int(input("1 - $10, 2 - $15, 3 - $20, 4 - $12, 5 - $25"))
    print("Here are your items:", w_items)
    print("Total cost; $", walmart_prices[w_items])

if store == ("costco"):
    c_items = int(input("1 - $5, 2 - $20, 3 - $15, 4 - $10, 5 - $12"))
    print("Here are your items:", c_items)
    print("Total cost; $", costco_prices[c_items)])

if store == ("sprouts"):
    s_items = int(input("1 - $12, 2 - $8, 3 - $15, 4 - $20, 5 - $18"))
    print("Here are your items:", s_items)
    print("Total cost; $", sprouts_prices[s_items)])

当我在项目用户输入中输入多个值时,它给了我一个错误“int() 的无效文字与基数:

我想知道问题的解决方案是什么。我是 Python 新手,所以任何帮助都很棒:)

标签: python

解决方案


Wellint将尝试接受您提供的任何输入并将其转换为单个数字。由于它不能对诸如“1 2 3 1 4”之类的东西执行此操作,因此它会告诉您它不能将其转换为单个整数。这就是你得到的错误。

所以你需要做的是:决定你想认为什么样的输入是有效的,然后正确地解析它。喜欢...

inputs = input("blablabal").split(" ")

这将通过在空格处拆分用户输入来获取用户输入input并将其转换为输入列表

然后你可以把每一个都变成整数,比如

w_items = [int(item) for item in inputs]


推荐阅读