Handling User Input Errors in Python
ICT | Grade 9 | Language Schools
Unit 1: Artificial Intelligence and Programming Languages
Lesson 5Introduction
Programs often ask users to enter information. Sometimes the user enters unexpected or invalid data.
A good Python program should handle these situations instead of stopping suddenly with an error message.
🎥 Lesson Video
Watch the video first, then study the examples and complete the interactive quiz at the end of the lesson.
Learning Objectives
Identify common problems caused by invalid user input.
Recognize when Python cannot convert an input to the required value.
Handle selected errors without stopping the whole program.
Write programs that respond clearly when users enter invalid data.
1. Getting Input from the User
Python uses the input() function to receive information
from the user.
The user enters a value, and Python stores it in the variable
name.
input() is normally a string.
2. Converting User Input to an Integer
If we want to use the input as an integer, we can use
int().
This works when the user enters a valid integer such as
14.
3. What Happens with Invalid Input?
Suppose the program expects a number but the user enters text.
If the user enters:
Python cannot convert that text into an integer. This can produce a ValueError.
4. What Is ValueError?
ValueError occurs when an operation receives a value of
an appropriate general type but the value itself is not suitable for
the operation.
The string cannot be converted into an integer, so Python raises
a ValueError.
5. The try Statement
We can place code that might cause an exception inside a
try block.
Python first tries to execute the code inside the
try block.
6. The except Statement
The except block specifies what Python should do when
a matching exception occurs.
If the user enters something that cannot be converted to an integer,
the except ValueError block handles the problem.
7. Complete Example
If the user enters 15, the program displays the age.
If the user enters abc, the program displays a helpful
message instead.
8. Asking the User to Try Again
We can combine try and except with a loop
so the program continues asking until the user enters a valid number.
The loop continues after an invalid input and stops when a valid integer is entered.
9. Handling Decimal Numbers
The same idea can be used when the program expects a decimal number.
The float() function converts suitable input into a
floating-point number.
10. Input Validation
Handling errors is one part of creating reliable programs. Another important idea is input validation.
Input validation means checking whether the user's data meets the requirements of the program.
Suppose a program asks for an age between 1 and 120.
11. Handling Different Errors
A program may need to handle different types of exceptions.
Each except block handles a particular type of exception.
12. The else Block
Python also allows an optional else block.
It runs when the try block finishes without an exception.
else runs only when no exception occurs in the
corresponding try block.
13. Good Programming Practices
- Ask the user clearly for the required information.
- Convert the input to the correct data type when necessary.
-
Use
tryaround operations that may raise a known exception. -
Use specific exceptions such as
ValueErrorwhen possible. - Give the user a clear and helpful error message.
- Allow the user to correct the input when appropriate.
14. Common Mistakes
Mistake 1: Using int() without handling invalid input
This may raise a ValueError when the user enters
invalid text.
Mistake 2: Catching every possible error without a reason
It is generally better to handle the specific exceptions that the program expects rather than hiding unexpected problems.
Mistake 3: Giving unclear messages
Instead of saying only "Error", tell the user what kind of input is expected.
15. Practical Example: Student Score
Let's create a program that asks for a student's score and checks whether the input is valid.
This example combines:
input()int()tryexceptValueError- input validation using
if
Quick Review
- input(): Gets information from the user.
- int(): Converts suitable input to an integer.
- float(): Converts suitable input to a floating-point number.
- ValueError: Occurs when a value is not suitable for an operation.
- try: Contains code that may raise an exception.
- except: Handles a matching exception.
- else: Runs when the try block finishes without an exception.
- Validation: Checks whether input meets the program's requirements.
📝 Interactive Quiz
Test your understanding of handling user input errors in Python. Choose one answer for each question.
1. Which function is used to get input from the user?
2. What does input() normally return?
3. Which exception commonly occurs when int() cannot convert input?
4. Which keyword is used to start exception-handling code?
5. Which keyword handles a matching exception?
6. What is the purpose of input validation?
7. Which code correctly handles invalid integer input?
8. What does the else block do in try/except?
9. Which function converts suitable input into a decimal number?
10. Why should programs give clear error messages?
No comments:
Post a Comment