Looping statements
Sure! Below are examples of for loop and while loop in Python, each with a short explanation
and solution.
✅ 1. for Loop Example: Print numbers from 1 to 5
# Using for loop
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
✅ 2. while Loop Example: Print numbers from 1 to 5
# Using while loop
i=1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
✅ 3. for Loop: Print even numbers from 2 to 10
for i in range(2, 11, 2):
print(i)
Output:
2
4
6
8
10
✅ 4. while Loop: Sum of numbers from 1 to 5
i=1
total = 0
while i <= 5:
total += i
i += 1
print("Sum is:", total)
Output:
Sum is: 15
✅ 5. for Loop: Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
✅ 6. while Loop: Print countdown from 5 to 1
i=5
while i >= 1:
print(i)
i -= 1
Output:
5
4
3
2
1
Would you like examples with break or continue also?
Great! Here are examples of for and while loops using break and continue in Python:
---
✅ 7. for Loop with break: Stop at number 3
for i in range(1, 6):
if i == 3:
break
print(i)
Output:
1
2
Explanation: The loop stops (breaks) when i becomes 3.
---
✅ 8. while Loop with break: Stop at 3
i=1
while i <= 5:
if i == 3:
break
print(i)
i += 1
Output:
1
2
---
✅ 9. for Loop with continue: Skip number 3
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
Explanation: The loop skips printing 3 using continue.
---
✅ 10. while Loop with continue: Skip 3
i=0
while i < 5:
i += 1
if i == 3:
continue
print(i)
Output:
1
2
4
5
Great! Here are some real-world tasks and nested loop examples using for and while loops in
Python. These are practical and often asked in exams or interviews.
---
✅ 11. Pattern Printing with for Loop
Print a right-angled triangle of stars (*):
rows = 5
for i in range(1, rows + 1):
print("*" * i)
Output:
*
**
***
****
*****
---
✅ 12. Multiplication Table using while Loop
num = 3
i=1
while i <= 10:
print(f"{num} x {i} = {num * i}")
i += 1
Output (Table of 3):
3x1=3
3x2=6
...
3 x 10 = 30
---
✅ 13. Nested for Loop: Multiplication Tables from 1 to 3
for i in range(1, 4): # Tables 1 to 3
for j in range(1, 6): # Multiply up to 5
print(f"{i} x {j} = {i * j}")
print("-----")
Output:
1x1=1
1x2=2
...
3 x 5 = 15
---
✅ 14. Sum of All Even Numbers (1 to 100) using while
i=1
total = 0
while i <= 100:
if i % 2 == 0:
total += i
i += 1
print("Sum of even numbers from 1 to 100:", total)
Output:
Sum of even numbers from 1 to 100: 2550
---
✅ 15. Search an Item in List using for Loop
names = ["Aman", "Rita", "Sita", "Ravi"]
search = "Rita"
for name in names:
if name == search:
print("Name found:", name)
break
else:
print("Name not found")
Output:
Name found: Rita