2017-10-07 149 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語句它假設是

如果選擇的縮進錯誤=「是」: