Search code examples
pythonwhile-looptry-catchexcept

Loop that uses try/except for input and loops until 'done' is entered


I'm kind of new to coding in Python and I'm trying to write a loop that asks for numerical input and reads it until the user inputs "done", where it will then exit the loop and print the variables: number, count and average. (not trying to store anything in a list)

I also want it to print "invalid input" and continue the loop if the user enters anything that isn't an integer, unless its "done".

Unfortunately it returns "invalid input" and keeps looping even when I enter "done". What am I doing wrong? Could anyone point me in the right direction?

number = 0
count = 0
avg = 0
inp = 0
while True:
    try:
        inp = int(raw_input('Enter a number: '))
        if inp is 'done':    
            number = number + inp
            count = count + 1
            avg = float(number/count)
            break
    except:
        print 'Invalid input'
print number
print count
print float(avg)

Solution

  • sum = 0.0
    count = 0
    while True:
        inp = raw_input('Enter a number: ')
        if inp == 'done':
            break
        try:
            sum += int(inp)
            count += 1
        except ValueError:
            print 'Invalid input'
    print sum
    print count
    if count != 0:  # Avoid division by zero
        print sum / count