在python 3.6中列出和转换用户输入

时间:2017-03-23 02:09:19

标签: list python-3.x input

您好,我无法弄清楚如何将我的总购物价格加在一起并显示总数。我搜索这个,我无法找到我正在寻找:( 谢谢!

print("Hello this is your shopping list!")

shopList = []
shoppingTotal = []
sumOfAllNumbers = sum(shoppingTotal)

maxLengthList = 2
while len(shopList) < maxLengthList:
    item = input("what do you need today? Add your item: ")
    shopList.append(item)
    price = int(input("How much can you spend?"))
    shoppingTotal.append(price)
    print(shopList)
    print(shoppingTotal)
print("This is your shopping list")
print(shopList)
print(sumOfAllNumbers + 'This will be your budget for today')

1 个答案:

答案 0 :(得分:0)

您的问题是,您在拥有完整列表之前已定义sumOfAllNumbers。当你说:

sumOfAllNumbers = sum(shoppingTotal)
在您设置时,

sumOfAllNumbers将设置为列表shoppingTotal 中所有值的总和。在你的代码中,你正在做:

shoppingTotal = []
sumOfAllNumbers = sum(shoppingTotal)

用它们的值替换变量,我们可以看到你正在做的是:

sumOfAllNumbers = sum([])

显然是0。

您应该做的是在> 之后将列表加上>,并为其添加价格。

此外,您无法直接将sumOfAllNumbers添加到字符串中 - 虽然可以添加数字和字符串,但Python不会自动转换值以将其添加到另一个 - 所以您需要首先使用str()函数手动转换sumOfAllNumbers。

所以你的代码应该是这样的:

print("Hello this is your shopping list!")

shopList = []
shoppingTotal = []

maxLengthList = 2
while len(shopList) < maxLengthList:
    item = input("what do you need today? Add your item: ")
    shopList.append(item)
    price = int(input("How much can you spend?"))
    shoppingTotal.append(price)
    print(shopList)
    print(shoppingTotal)


print("This is your shopping list")
print(shopList)

sumOfAllNumbers = sum(shoppingTotal)
print(str(sumOfAllNumbers) + 'This will be your budget for today')

此外,最后一点:您的变量名称不是Pythonic。 Python中的常规做法是使用snake_case而不是camelCase。因此sumOfAllNumbers应该被称为sum_of_all_numbers