When input goes wrong: ValueError
Programs meet users, and users type surprising things. Look at the program that reads how many books you have and adds 1. If the user types 7, it works. If the user types the word seven, int() cannot make a whole number from it and Python stops with a ValueError. Everything after that line is never run. The table shows more cases. An empty text fails. A decimal such as 5.5 fails too, because int() accepts only a whole number written with digits; it does not cut the decimal part off. The aim of the next lessons is a program that does not crash on a wrong input but helps the user to try again. Remember Week 1: this is the problem we met with five.
| What the user types | What int() does |
|---|---|
| "7" | 7 |
| "seven" | ValueError |
| "" (nothing) | ValueError |
| "5.5" | ValueError |
1books = int(input("How many books? ")) 2print("Next year:", books + 1)
How many books? 7 Next year: 8
1books = int(input("How many books? ")) 2print("Next year:", books + 1)
How many books? seven ValueError: the text is not a whole number
A program reads how many pencils you have. Make a table of four things a user might type: two that work and two that fail. For each failing one, say why int() cannot convert it. Use only invented inputs.