PY4E chapter5 Iterations-Exercise 1

小白学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)

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值