Interactive Loop

In [5]:
def average2():
    _sum = 0.0
    count = 0
    moredata = True
    
    #while moredata is True:
    while moredata:
        try:
            x = float(input("Enter a number >> "))
        except ValueError:
            print("Invalid input!")
            continue
            
        _sum = _sum + x
        count = count + 1
        
        response = input("Do you have more numbers to enter? (yes/no): ")
        if response[0] == "y":
            moredata = True
        else:
            moredata = False
        
    print("\nThe average of the numbers is", _sum/count)    
In [6]:
average2()
Enter a number >> 10
Do you have more numbers to enter? (yes/no): y
Enter a number >> foobar
Invalid input!
Enter a number >> n
Invalid input!
Enter a number >> 10
Do you have more numbers to enter? (yes/no): n

The average of the numbers is 10.0
In [ ]: