2017-02-13 while学习习题

Exercise 1:
Write a program which repeatedly reads numbers until the user enters "done". Once "done" is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.

total = 0
count = 0
while True:
    number = input('Enter a number: ')
    if number == 'done':
        break
    try:
        number = int(number)
    except:
        print("Invalid input")
        continue
    total += number
    count += 1
    average = total/float(count)
print(total, count, average)

运行结果如下:

Enter a number: hh
Invalid input
Enter a number: 566
Enter a number: 236
Enter a number: 59
Enter a number: 8999
Enter a number: 547
Enter a number: done
10407 5 2081.4


Exercise 2:
Write another program that prompts for a list of numbers as above and at the end prints out both the maximum and minimum of the numbers instead of the average.

list = []
while True:
    line = input('Enter a number: ')
    if line == 'done':
        break
    try:
        number = int(line)
        list.append(number)
    except:
        print('Invalid number')
        continue


print('The maximum number is:', max(list),'\nThe minimum number is:', min(list))

运行结果如下:

Enter a number: 0
Enter a number: 2
Enter a number: 6
Enter a number: -8
Enter a number: 99
Enter a number: -89
Enter a number: 998
Enter a number: wrong
Invalid number
Enter a number: 87[
Invalid number
Enter a number: done
The maximum number is: 998
The minimum number is: -89

你可能感兴趣的:(2017-02-13 while学习习题)