题目要求:
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)
用到的知识点:
- try/except 抛出异常后,用continue 结束本次循环进入下次循环,阻止循环终止。
- while 是 indefinite iteration; for 是definite iteration。区别在于:for 在循环体之前就知道循环的次数。
- python 的数据格式:Int, Float, String, Boolean,None
- break: Exits the currently executing loop
- continue: Jumps to the "top" of the loop and starts the next iteration
- 'is' and 'is not' Operators:
- both use in logic expressions
- 'is': similar to, but stronger than ==, implies 'is the same as'
- you shouldn’t use 'is' when you should use '=='
- 'is' used for 'True', 'False', 'None'.
- don’t use 'is' frequently, cause it’s strong equality, stronger than ==