在python中打印while循环的总和

时间:2017-10-07 05:02:20

标签: python

def main():
    import math
#the loop
choice=str(raw_input("Will you add an item to the list? Say 'yes' to add or 'no' once you're done"))
while choice== "Yes" or choice== "yes":
    addItem=input("What is the item?")
    additemP=input("How much does that cost?")
    print(addItem + "---------------------$" + additemP)
    choice=str(raw_input("Will you add an item to the list? Just say yes or no"))
if choice != "yes":
    quit
    total = sum(additemP)

    print(total)

每次我结束循环时,我的列表输出显示我命名的项目及其价格,但我无法获得打印的总数我只收到错误消息

  

TypeError:+:' int'不支持的操作数类型和' str'第14行

我刚刚开始编码,而且我不太清楚该怎么做

4 个答案:

答案 0 :(得分:1)

你在这里犯了两个错误。

1)input()将返回您键入的字符串。所以当你添加addItemP时,这是成本,它只是一个字符串,而不是一个int。所以sum(addItemP)不起作用。使用int(addItemP)将其转换为int

2)您没有使用列表。否则总数将只有最后一项的成本。

这应该有用。

def main():
    import math
#the loop
PriceList=[]
choice=str(input("Will you add an item to the list? Say 'yes' to add or 'no' once you're done"))
while choice== "Yes" or choice== "yes":
    addItem=input("What is the item?")
    additemP=input("How much does that cost?")
    PriceList.append(int(additemP))
    print(addItem + "---------------------$" + additemP)
    choice=str(input("Will you add an item to the list? Just say yes or no"))
if choice != "yes":
    quit

total = sum(PriceList)

print(total)

答案 1 :(得分:0)

您需要使用列表。

choice=str(raw_input("Will you add an item to the list? Say 'yes' to add or 'no' once you're done"))
listofprices=[]
while choice== "Yes" or choice== "yes":
    addItem=input("What is the item?")
    additemP=input("How much does that cost?")
    listofprices.append(int(additemP))
    print(addItem + "---------------------$" + additemP)
    choice=str(input("Will you add an item to the list? Just say yes or no"))
    if choice != "yes":
       total = sum(listofprices)
       break
print(total)

答案 2 :(得分:0)

你需要使用list,因为sum函数使用循环来添加像

这样的值
sum([1,2,3,4])

 iter=[1,2,3]
 sum(iter)

答案 3 :(得分:0)

在if语句中有一个缩进错误,它假设是

如果选择!=“是”:       放弃 打印(总)