1
votes
purchase_amounts = []

user = input("enter your prices: ")

while user != "done":
  purchase_amounts += user
  user = input("enter your prices: ")
  if user == "done":
    print(purchase_amounts)
    break

I want the code to print the sum of user price and when user inputs done the program ends

# right now the output is:
# enter your prices: 12
# enter your prices: 15
# enter your prices: done
# ['1', '2', '1', '5']
1
Reminder - input from user is string. You have to convert it to int. Try to see the execution in here pythontutor.com - Daniel Hao
Does this answer your question? How can I read inputs as numbers? - fsimonjetz

1 Answers

0
votes
def question():
    purchase_amounts = []
    while True:
        user = input("enter your prices: ")
        purchase_amounts.append(user)
        if user == "done":
            print(purchase_amounts)
            return add(purchase_amounts)


def add(array):
    ans = 0
    for num in array[:-1]:
        ans += int(num)
    return ans


print(question())

Close! To answer your first question you are adding to a list instead of appending thus you are adding individual characters as strings.

I rewrote your question with two functions one main function then one helper. So while True is basically an infinite loop until we return. You keep asking the user input questions in the loop and then once you find done you call the add() function. From here you sum the array sliced removed the last index which is not inclusive in the slice.