2017-10-07 147 views
1
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) 
我每次结束循环我的列表中的输出显示我命名的项目及其价格

,但我不能得到总打印出来,我只得到一个错误信息打印总和为while循环蟒蛇

TypeError: unsupported operand type(s) for +: 'int' and 'str' on line 14

我刚开始编码最近,我也不太清楚该怎么做

+1

你为什么要使用的raw_input和输入退出 打印(总)。如果您使用的是Python 3,只需使用输入 –

+0

我相信''loop''应该在''main''函数中。如果是这样,请相应缩进代码。如果不是,那么你可以去掉''main''函数,因为它什么都不做。 –

+0

@Silencer,我相信**原来的代码是为python2 **而设计的。 **编辑版本是严格的python3 **,因此答案会松动python2的一些细微差别。 ''raw_input()''将用户输入隐式转换为字符串。而''input()''只接受数字。将不能被解释为数字的输入传递给''input()''引发''NameError''。请重新提出问题以反映op的原始含义。 –

回答

1

你在这里做了两个错误值。

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

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) 
+0

附近谢谢你真的很有帮助。我对编码知之甚少,我只是一个刚刚开始学习的学生,但这有助于澄清一些事情对我有用。 +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) 
0

您需要使用名单,因为SUM函数使用循环添加像

sum([1,2,3,4]) 

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

sum函数不需要4个参数。答案的第一部分是不正确的。 –

+0

我忘了把[]放在 –

0

有一个在if语句它假设是

如果选择的缩进错误=“是”: