☰ خطة العام · تكنولوجيا المعلومات والاتصالات (بالإنجليزية)

When input goes wrong

الأسبوع 9 · الدرس ٥ «معالجة أخطاء مدخلات المستخدم في لغة Python»: ValueError وtry وexcept وإعادة المحاولة · 3 دروس
1

When input goes wrong: ValueError

ICT Prep 3 Term 1, Unit 1, Lesson 5: pp. 54–63
GoalExplain why a wrong input stops a program with a ValueError and say which typed texts int() accepts.
New words
error · a problem that makes Python stop the programValueError · the error shown when a value has the right type but cannot be convertedinvalid input · something typed that the program cannot usecrash · when a program stops because of an error
Explanation

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 typesWhat int() does
"7"7
"seven"ValueError
"" (nothing)ValueError
"5.5"ValueError
Worked examples
Python
1books = int(input("How many books? "))
2print("Next year:", books + 1)
Output
How many books? 7
Next year: 8
The program works when the user types 7: it shows Next year: 8.
Python
1books = int(input("How many books? "))
2print("Next year:", books + 1)
Output
How many books? seven
ValueError: the text is not a whole number
The user types the word seven. int() cannot convert it, so Python stops at once with a ValueError and the last line never runs.
Class activity

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.

Practice
1
What does int("seven") cause?
2
Does int("5.5") give 5?
3
What happens to the lines after the line that causes the error?
4
What does the program show if the user types 12?