Handling User Input Errors in Python | ICT | Grade 9

💻

Handling User Input Errors in Python

ICT | Grade 9 | Language Schools

Unit 1: Artificial Intelligence and Programming Languages

Lesson 5

Introduction

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.

Key Idea: User input should be checked and handled carefully so that the program can continue working when the user enters invalid data.

🎥 Lesson Video

Watch the video first, then study the examples and complete the interactive quiz at the end of the lesson.

Learning Objectives

1. Understand Input Errors

Identify common problems caused by invalid user input.

2. Understand ValueError

Recognize when Python cannot convert an input to the required value.

3. Use try and except

Handle selected errors without stopping the whole program.

4. Build Safer Programs

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.

name = input("Enter your name: ") print("Hello", name)

The user enters a value, and Python stores it in the variable name.

Remember: The value returned by 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().

age = int(input("Enter your age: ")) print("Your age is", age)

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.

age = int(input("Enter your age: "))

If the user enters:

fourteen

Python cannot convert that text into an integer. This can produce a ValueError.

Problem: If an expected numeric value cannot be created from the user's input, the program may stop with an exception.

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.

Example:
number = int("hello")

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.

try: number = int(input("Enter a number: "))

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.

try: number = int(input("Enter a number: ")) except ValueError: print("Please enter a valid number.")

If the user enters something that cannot be converted to an integer, the except ValueError block handles the problem.

Result: Instead of suddenly stopping with an unhandled error, the program can give the user a clear message.

7. Complete Example

try: age = int(input("Enter your age: ")) print("Your age is", age) except ValueError: print("Please enter a valid integer.")

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.

while True: try: number = int(input("Enter a number: ")) break except ValueError: print("Invalid input. Try again.") print("You entered:", 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.

try: price = float(input("Enter the price: ")) print("Price:", price) except ValueError: print("Please enter a valid 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.

Example:

Suppose a program asks for an age between 1 and 120.

try: age = int(input("Enter your age: ")) if age < 1 or age > 120: print("Age must be between 1 and 120.") else: print("Valid age:", age) except ValueError: print("Please enter a number.")

11. Handling Different Errors

A program may need to handle different types of exceptions.

try: number = int(input("Enter a number: ")) result = 100 / number except ValueError: print("Please enter a valid integer.") except ZeroDivisionError: print("You cannot divide by zero.")

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.

try: number = int(input("Enter a number: ")) except ValueError: print("Invalid number.") else: print("Valid number:", number)
Remember: else runs only when no exception occurs in the corresponding try block.

13. Good Programming Practices

  1. Ask the user clearly for the required information.
  2. Convert the input to the correct data type when necessary.
  3. Use try around operations that may raise a known exception.
  4. Use specific exceptions such as ValueError when possible.
  5. Give the user a clear and helpful error message.
  6. Allow the user to correct the input when appropriate.

14. Common Mistakes

Mistake 1: Using int() without handling invalid input

age = int(input("Enter age: "))

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.

try: score = int(input("Enter your score: ")) if score < 0 or score > 100: print("Score must be between 0 and 100.") else: print("Valid score:", score) except ValueError: print("Please enter a whole number.")

This example combines:

  • input()
  • int()
  • try
  • except
  • ValueError
  • 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

التصنيفات

```html ```html ```