I'm a Python noob trying to make a program where the user will enter as many integers as they want and have the program calculate the total sum. They have to type the word "done" to execute the sum calculation. When I ran my program, I tped in 'done' and got an error saying "invalid literal for int() with base 10: 'done'" Any feedback/help will be great.

user_inputs = []

while True:

user_inputs = int(user_inputs)

if user_inputs == str("done"):
print("The sum of your numbers is " + user_inputs)

Recommended Answers

All 4 Replies

As you noticed, feeding a string that doesn't represent an integer (like "done") to int will cause an exception. So you should only call int on the user input if it is not "done". You can achieve this by putting the if above the call to int and put the call to int in the else part of the if.

PS: Instead of str("done") you can just write "done".

PPS: Note that writing "done" will currently only cause the sum to be printed -- it will not stop the loop from further asking for input.

if user_input == "done" then output the answer and quit,
ELSE, add user_input to the list of inputs.

Not--
add user_input to the list
THEN if user_input == "done"

Take a close look t this ...

user_input_list = []

while True:
    user_input = input("Enter an integer: ")

    # condition to exit loop
    if user_input == "done":
        break

    user_input_list.append(int(user_input))
    #print(user_input_list) # test
    print("The sum of your numbers is {}".format(sum(user_input_list)))
def x():
    sum = 0
    lst = []
    while 1:
        inp = input('enter a number:\n')
        if inp == 'done':
            break
        lst.append(int(inp))
        sum += inp
        print sum
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.