美文网首页
2017-02-13 while学习习题

2017-02-13 while学习习题

作者: 终焉的灰烬 | 来源:发表于2017-02-13 21:41 被阅读0次

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学习习题

    Exercise 1:Write a program which repeatedly reads numbers...

  • 习题 33 while 循环

    习题 33 while 循环 结果:

  • 3.循环结构

    while循环结构 while(循环条件){循环操作} 练习题 老师每天检查张三的学习任务是否合格,如果不合格,则...

  • 12月1日—语言篇

    今天上午讲解了昨天的习题,以及学习了两个新的语句,while ,switch,两个语句,while语句和for语句...

  • [习题9]while

    使用教材 《“笨办法” 学C语言(Learn C The Hard Way)》https://www.jiansh...

  • 长光培训第12天

    上午 1.继续往下学习了字符串和while循环的相关内容 下午 2.做练习题

  • 叶子带你学 Python | (三)更多变量类型

    习题答案 作业一:使用 while 循环结构,因为需要在有评论时执行回复操作,没有评论时什么也不做。使用while...

  • Python Day17 list及tuple复习

    之前学习while一直有纠结的地方,先整理下,还是以fishc的练习题为例。 结果示例 1、list 如果访问li...

  • 2021-01-19python之while与死循环

    方案一:while后面的条件不为恒定值解决办法:while后面的条件随着循环次数执行的次数变化而变化 练习题:1....

  • 前端 while循环练习题

    用while循环重写小明的成绩,如果用户输入不合法就反复输入,直到正确为止 假如投资的年利率为5%,试求从1000...

网友评论

      本文标题:2017-02-13 while学习习题

      本文链接:https://www.haomeiwen.com/subject/gcbtwttx.html