Dalton Scurnopoli
Dalton Scurnopoli

Reputation: 13

printing the total sum for a while loop in 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)

every time i end the loop my output of the list shows the items i named and their price, but i can not get the total to print out i only get an error message

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

I just started coding very recently and I'm not too sure what to do

Upvotes: 1

Views: 2659

Answers (4)

Mohit Motwani
Mohit Motwani

Reputation: 4792

You're making two mistakes here.

  1. input() will return the string of whatever you type. So when you add in addItemP, which is the cost, its only a string and not an int. Hence, sum(addItemP) won't work. Convert it to int using int(addItemP)

  2. You aren't using a list. Otherwise the total will only have the cost of the last item.

This should work.

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)

Upvotes: 1

Olafusi Emmanuel
Olafusi Emmanuel

Reputation: 40

There is an Indentation error at the if statement it suppose to be

If choice !="yes": quit Print(total)

Upvotes: 0

Huzail Spy
Huzail Spy

Reputation: 5

You need to use list because sum function use loop to add values like

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

or

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

Upvotes: 0

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

You need to use a list.

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)

Upvotes: 0

Related Questions