Named errors and trying again with a loop
One try block can have several except blocks, each for a different error. The program below divides 10 by a typed number. A word causes a ValueError, and the typed value 0 causes a ZeroDivisionError. The two messages are different, because the two mistakes need different advice. Put the specific names first; the general name is Exception, and there is no name Error. To ask again after a wrong input, put the try inside while True. When the input is good, break leaves the loop. When it is bad, the except block shows a message and the loop starts again. The same idea works inside a function (remember Week 8).
1try: 2 num = int(input("Divide 10 by: ")) 3 print(10 / num) 4except ValueError: 5 print("Please type digits only.") 6except ZeroDivisionError: 7 print("You cannot divide by zero.")
Divide 10 by: 0 You cannot divide by zero.
1while True: 2 try: 3 num = int(input("Enter a number: ")) 4 print("You entered:", num) 5 break 6 except ValueError: 7 print("Numbers only, try again.")
Enter a number: abc Numbers only, try again. Enter a number: Numbers only, try again. Enter a number: 6 You entered: 6
1def to_number(text): 2 try: 3 return int(text) 4 except ValueError: 5 return 0 6 7print(to_number("12")) 8print(to_number("abc"))
12 0
1print(int("10") / int("2"))5.0
Plan a program that asks for the number of pencils and repeats the question until the user types a whole number that is 1 or more. Draw the loop as a flow, and write the two messages: one for a word and one for 0 or less. Test it with the typed values zero, ten and 3.