Hi friends, welcome to DailyCodeHub. Today we are going to learn how to check if a number is even or odd in Python. This is one of the most commonly asked programs in every python interview for freshers.
Question: Write a python program to check if a number is even or odd.
Method 1: Using the modulus operator
Code:
# Check even or odd using modulus operator
n = int(input("Enter a number: "))
if n % 2 == 0:
print(n, "is Even")
else:
print(n, "is Odd")
Output:
Enter a number: 10
10 is even.
Enter a number: 7
7 is odd.
Method 2: Using Bitwise AND
Code:
# Check even or odd using bitwise AND
n = int(input("Enter a number: "))
if n & 1 == 0:
print(n, "is Even")
else:
print(n, "is Odd")
Output:
Enter a number: 10
10 is Even
Method 3 : Using Ternary Operator
Code :
# Check even or odd using ternary operator
n = int(input("Enter a number: "))
result = "Even" if n % 2 == 0 else "Odd"
print(n, "is", result)
Output:
Enter a number: 10
10 is even.
Explanation :
Step 1 : We take a number as input form the user and convert it to integer using int( ).
Step 2 : In method 1, we use the % operator called modulus operator. It gives the remainder when a number is divided by 2.
Step 3 : If n % 2 == 0 it means no remainder. so the number is even.
Step 4 : If n % 2! = 0 it means remainder is 1. so the number is odd.
Step 5 : In method 2, we use bitwise AND operator with 1 . If the last bit is 0 the number is even. If last bit is 1 the number is odd.
Step 6 : In method 3 we use ternary operator to write the same logic in just one line.
Key points :
Even numbers are divisible by 2 with no remainder
Odd numbers give remainder 1 when divided by 2
% operator is called modulus operator
n % 2 == 0 means even number
n % 2 ! = 0 means odd number
0 is considered an even number in python
I hope this program was helpful. if you have any doubts please leave a comment below. keep practicing and happy coding.
Happy coding ❤️
No comments:
Post a Comment