小白学Python, 最开始不会做这道题,想用列表的方式计数、求和、求平均数,但就是写不出来,主要卡壳在while语句和try/except,还非常不熟练,这是参考网上关于while和try/excepet的写法,自己用列表的方式写了一下,仅作为个人的自学记录。
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.
from numpy import average
num_list = []
while True:
num = input("Enter a number: ")
if num == 'Done' or num == 'done':
break
try:
num = eval(num)
num_list.append(num)
except:
print('Invalid')
continue
count_num = len(num_list)
total_num = sum(num_list)
average_num = average(num_list)
print(count_num, total_num, average_num)