Sentinel Loops

In [1]:
def main():
    _sum= 0.0
    count = 0
    x = float(input("Enter a number (negative to quit) >> "))
    while x >= 0:
        _sum += x
        count += 1
        x = float(input("Enter a number (negative to quit) >> "))
    print("\nThe average of the numbers is {0:0.2f}".format(_sum/count))
In [2]:
main()
Enter a number (negative to quit) >> 3
Enter a number (negative to quit) >> 345
Enter a number (negative to quit) >> 23
Enter a number (negative to quit) >> 7
Enter a number (negative to quit) >> 23
Enter a number (negative to quit) >> -1

The average of the numbers is 80.20
In [3]:
def main2():
    _sum= 0.0
    count = 0
    x_str = input("Enter a number (press enter to quit) >> ")
    while x_str != "":
        x = float(x_str)
        _sum += x
        count += 1
        x_str = input("Enter a number (press enter to quit) >> ")
    print("\nThe average of the numbers is {0:0.2f}".format(_sum/count))
In [4]:
main2()
Enter a number (press enter to quit) >> 34
Enter a number (press enter to quit) >> 456
Enter a number (press enter to quit) >> -23
Enter a number (press enter to quit) >> 245
Enter a number (press enter to quit) >> -536
Enter a number (press enter to quit) >> -23
Enter a number (press enter to quit) >> 

The average of the numbers is 25.50