π Day 27/150 – Print Even Numbers up to N in Python
Printing even numbers up to N is a great way to understand loops, conditions, and number patterns in Python.
π An even number is any number divisible by 2.
Let’s explore different approaches π
πΉ Method 1 – Using for Loop
The most efficient and recommended method.
n = 10
for i in range(2, n + 1, 2):
print(i)
✅ Explanation:
- Starts from 2
- Increments by 2
- Directly prints only even numbers
πΉ Method 2 – Using Condition inside Loop
Check each number manually.
n = 10
for i in range(1, n + 1):
if i % 2 == 0:
print(i)
✅ Explanation:
- % 2 == 0 checks if a number is even
- Prints only when condition is true
πΉ Method 3 – Taking User Input
Make your program dynamic.
n = int(input("Enter a number: ")) for i in range(2, n + 1, 2): print(i)
πΉ Method 4 – Using while Loop
A condition-based approach.
n = 10 i = 2 while i <= n: print(i) i += 2
✅ Explanation:
- Starts from 2
- Runs until i <= n
- Increments by 2
π― Final Thoughts
- Best approach: range(2, n+1, 2) ✅
- Condition method builds logic understanding π§
- while loop helps with control-based problems π


0 Comments:
Post a Comment