zoukankan      html  css  js  c++  java
  • Python: find the smallest and largest value

    题目要求:

    Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below. [ Programming for Everybody (Getting Started with Python) 5.2 assignment ]

    largest = None
    smallest = None
    while True:
        num = input("Enter a number: ")
        if num == "done" : break
        try:
            value = int(num)
        except:
            print("Invalid input")
            continue
        if largest is None or smallest is None:
            largest = value
            smallest = value
        elif smallest > value:
            smallest = value    
        elif largest < value:
            largest = value
    print("Maximum is", largest)
    print("Minimum is", smallest)

    用到的知识点:

    1. try/except 抛出异常后,用continue 结束本次循环进入下次循环,阻止循环终止。
    2. while 是 indefinite iteration; for 是definite iteration。区别在于:for 在循环体之前就知道循环的次数。
    3. python 的数据格式:Int, Float, String, Boolean,None
    4. break: Exits the currently executing loop
    5. continue: Jumps to the "top" of the loop and starts the next iteration
    6. 'is' and 'is not' Operators: 
      1. both use in logic expressions
      2. 'is': similar to, but stronger than ==, implies 'is the same as' 
      3. you shouldn’t use 'is' when you should use '=='
      4. 'is' used for 'True', 'False', 'None'.
      5. don’t use 'is' frequently, cause it’s strong equality, stronger than ==
  • 相关阅读:
    学习Node.js笔记(一)
    HTML5的新特性及技巧分享总结
    前端切图的一些笔记(整理的有点乱)
    聊一聊前端速度统计(性能统计)那些事儿(转)
    jQuery中的checkbox问题
    随笔记录
    pillow模块快速学习
    Git学习及使用
    网站(陆续更新)
    ggplot笔记001——ggplot2安装
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10433232.html
Copyright © 2011-2022 走看看