☰ Year plan · Communication Technology

When input goes wrong

Week 9 · Unit 1, Lesson 5 Handling User Input Errors in Python · 3 lessons
3

Named errors and trying again with a loop

ICT Prep 3 Term 1, Unit 1, Lesson 5: pp. 54–63
GoalHandle different errors with separate except blocks and repeat the question until the input is good.
New words
ZeroDivisionError · the error shown when a number is divided by zerowhile True · a loop that repeats until a break leaves itbreak · leaves the loop at onceException · the general name for ordinary errors; there is no name Error
Explanation

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).

Python
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.")
Output
Divide 10 by: 0
You cannot divide by zero.
Worked examples
Python
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.")
Output
Enter a number: abc
Numbers only, try again.
Enter a number: 
Numbers only, try again.
Enter a number: 6
You entered: 6
The user types abc, then nothing, then 6. The first two inputs fail and show a message; the loop asks again. The third works, and break leaves the loop.
Python
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"))
Output
12
0
Error handling inside a function: to_number returns 0 when the text is not a whole number. Here 0 means no valid number. A real program may ask again instead.
Python
1print(int("10") / int("2"))
Output
5.0
Careful with division. int("10") / int("2") shows 5.0 and not 5, because the sign / always gives a decimal result (Week 2).
Class activity

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.

Practice
1
What does the first program show for the typed value 4?
2
Which error does 10 / 0 cause?
3
What does break do in the retry loop?
4
Is except Error a correct line?