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 ==
原文地址:https://www.cnblogs.com/Jessiezyr/p/10433232.html