In this step, you will learn how to validate the input type to ensure that the user enters an integer. This is important because the int() function will raise a ValueError if the input cannot be converted to an integer (e.g., if the user enters text).
To handle potential errors, you'll use a try-except block. This allows you to gracefully handle exceptions and prevent your program from crashing.
Open odd_numbers.py in the VS Code editor and replace the existing code with the following:
try:
number = int(input("Enter an integer: "))
if number % 2 == 0:
print(number, "is an even number.")
else:
print(number, "is an odd number.")
except ValueError:
print("Invalid input. Please enter an integer.")
Here's a breakdown of the code:
try:: This block contains the code that might raise an exception.
number = int(input("Enter an integer: ")): This line attempts to convert the user's input to an integer. If the input is not a valid integer, a ValueError will be raised.
if number % 2 == 0: and else:: These lines are the same as in the previous step, checking if the number is even or odd.
except ValueError:: This block catches the ValueError exception if it is raised in the try block.
print("Invalid input. Please enter an integer."): This line prints an error message if the user enters invalid input.
Save the odd_numbers.py file.
Now, run the script using the python command in the terminal:
python odd_numbers.py
The script will prompt you to enter an integer. Enter abc and press Enter:
Enter an integer: abc
You should see the following output:
Invalid input. Please enter an integer.
Run the script again and enter 7.5:
python odd_numbers.py
You should see the following output:
Invalid input. Please enter an integer.
Run the script again and enter 11:
python odd_numbers.py
Enter an integer: 11
11 is an odd number.
This demonstrates how to validate the input type and handle potential errors using a try-except block. This is a crucial skill for writing robust and user-friendly programs.