If you're learning Python, finding even numbers is a simple and useful beginner exercise.
An even number is a number that can be divided by 2 without any remainder.
For example:
2, 4, 6, 8, 10
Using the % Operator
In Python, we can use the modulus (%) operator to check whether a number is even.
num = 10
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
How does it work?
num % 2 gives the remainder after dividing the number by 2.
- Remainder
0→ Even number - Remainder
1→ Odd number
For example:
10 % 2 = 0
7 % 2 = 1
Finding Even Numbers from a List
We can also find even numbers from a list using a for loop.
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
for num in numbers:
if num % 2 == 0:
print(num)
Output
2
4
6
8
Conclusion
Finding even numbers is a simple Python problem, but it helps beginners understand important concepts like:
-
%operator if-else-
forloops - Lists
These basic concepts are useful for solving many programming problems.
Top comments (0)