☰ Year plan · Communication Technology

When input goes wrong

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

try and except: a program that does not crash

ICT Prep 3 Term 1, Unit 1, Lesson 5: pp. 54–63
GoalUse try and except ValueError so that a wrong input shows a helpful message, and know why a bare except is a weaker habit.
New words
try · the block where Python tries the risky linesexcept · the block that runs if the named error happenshandle an error · plan what the program does when an error happensbare except · an except with no error name; it catches every error
Explanation

The try and except blocks make a program calm when a mistake happens. Python first tries the lines under try. If everything works, the except block is skipped. If a ValueError happens, Python jumps straight to except ValueError and runs its lines. The message should tell the user what to do, such as Please type digits only, not just Error. There is a shorter form, a bare except with no error name. It catches every kind of error, even our own typing mistakes inside the try block, and then shows a message that is wrong. So the better habit is to name the error you expect. Note the layout: try: and except ValueError: are on their own lines, with the code under them indented.

Python
1try:
2    books = int(input("How many books? "))
3    print("Next year:", books + 1)
4except ValueError:
5    print("Please type digits only.")
Output
How many books? seven
Please type digits only.
Worked examples
TypedScreen shows
"7"Next year: 8
"seven"Please type digits only.
"" (nothing)Please type digits only.
"5.5"Please type digits only.
The table shows what the screen shows for four typed values. Only 7 is a whole number written with digits. The three other values go to the except block.
Python
1try:
2    books = int(input("How many books? "))
3    print("Next year:", bookz + 1)
4except:
5    print("Please type digits only.")
Output
How many books? 7
Please type digits only.
A bare except hides a mistake. Here the programmer typed bookz instead of books. The user types the good input 7, but the screen blames the user. With except ValueError, Python would show the real NameError and the slip would be found.
Class activity

On paper, write a try and except ValueError program that asks how many pencils there are and shows the number plus 10. Write a good message for the except block. Then say what the screen shows for the typed values 3 and three.

Practice
1
What does the picture program show for the typed value seven?
2
When is the except block skipped?
3
Why is Please type digits only a better message than Error?
4
Why is a bare except a weaker habit?