Project Overview 💡
In this beginner-friendly project, you’ll write a Python program that checks whether a number entered by the user is even or odd. This is a great way to practice input handling, number conversion, and conditional logic.
Challenge Yourself! 🚀
Before checking the solution, try writing a script that takes a number and prints whether it is even or odd.
Task:
Write a Python program that:
Asks the user to input a number
Converts it from string to integer
Uses the modulus operator to determine if it's even or odd
Prints the result accordingly
Expected Output:
(1) The program prompts the user to enter a number in the terminal:
(2) The user types in a number (e.g., 3) and presses Enter. The program checks the number and prints out either “The number X is odd.” or “The number X is even.” depending on the number:
Give it a shot! Scroll down when you're ready for the step-by-step guide.
Spoiler Alert!
Step-by-Step Guide
Step 1️⃣: Get User Input
Use the input()
function to get a number from the user as a string.
number = input("Enter a number: ")
Step 2️⃣: Convert to Integer
Convert the input string to an integer using int()
.
number = int(number)
Step 3️⃣: Use Modulus to Check Even/Odd
Use %
to check if the number is divisible by 2.
if number % 2 == 0:
Step 4️⃣: Display Result for Even
If divisible by 2, the number is even.
print(f"The number {number} is even.")
Step 5️⃣: Display Result for Odd
If not, it's odd.
else:
print(f"The number {number} is odd.")
Complete Code 🧨
# Step 1: Get user input
number = input("Enter a number: ")
# Step 2: Convert input to an integer
number = int(number)
# Step 3: Check if the number is even or odd
if number % 2 == 0:
# Step 4: Display the result if the number is even
print(f"The number {number} is even.")
else:
# Step 5: Display the result if the number is odd
print(f"The number {number} is odd.")
Alternative Solution
Here’s a version that includes error handling to prevent crashes if the user enters a non-numeric value:
try:
number = int(input("Enter a number: "))
if number % 2 == 0:
print(f"The number {number} is even.")
else:
print(f"The number {number} is odd.")
except ValueError:
print("That's not a valid number. Please enter an integer.")
Comparison
The original version is concise and good for clean input.
The alternative version is more user-proof by handling errors gracefully.
Want More? 🔥
Enjoyed this project? Unlock real-world projects with full guides & solutions by subscribing to the paid plan. 🎉
num = int(input("Enter a number: "))
if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")