Practical 4: Program to Find Whether the Given Number is Even or Odd
Problem Statement
Write a Python program to determine whether a given number is even or odd.
- A number is considered even if it is divisible by 2 (i.e., the remainder when divided by 2 is 0).
- A number is considered odd if it is not divisible by 2 (i.e., the remainder when divided by 2 is 1).
The program should:
- Take an integer input from the user.
- Print whether the number is even or odd.
Solution Code
# Program to check if the number is even or odd
# Input: Take an integer number from the user
num = int(input("Enter a number: "))
# Check if the number is even or odd
if num % 2 == 0:
print(f"{num} is an even number.")
else:
print(f"{num} is an odd number.")
Output
- The program will ask the user to input a number.
- It will then print whether the number is even or odd based on the divisibility test.
Example outputs for different inputs:
For even numbers:
Enter a number: 16
16 is an even number.
Process finished with exit code 0
For odd numbers:
Enter a number: 9
9 is an odd number.
Process finished with exit code 0
Explanation
Below is the explanation of F.E. PPS Unit 2 Practical 4 solution where we have written Python Python program to determine whether a given number is even or odd.
- Input of Number:
- The program starts by asking the user to input a number. The input is taken using the input() function and converted to an integer using int().
- Divisibility Check:
- The program uses the modulus operator (%) to check the remainder when the number is divided by 2.
- If the remainder is 0 (num % 2 == 0), the number is even.
- If the remainder is 1, the number is odd.
- The program uses the modulus operator (%) to check the remainder when the number is divided by 2.
- Displaying the Result:
- The program prints whether the number is even or odd based on the result of the modulus operation.
Key Concept Learned
- Modulo Operation (%):
- The modulus operator is used to find the remainder when one number is divided by another. In this case, it helps determine whether a number is divisible by 2.
- Conditional Statements:
- The program uses an if-else statement to decide whether the number is even or odd, based on the result of the modulus operation.
- Input Handling and Conversion:
- The program demonstrates how to handle user input and convert it to the appropriate data type (integer) for performing arithmetic operations.