20 Python Loop Programs with Output
1. Print numbers from 1 to 5 (for loop)
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
2. Print numbers from 1 to 5 (while loop)
i = 1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
3. Even numbers from 2 to 10
for i in range(2, 11, 2):
print(i)
Output:
2
4
6
8
10
4. Odd numbers from 1 to 9
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
5. Sum of numbers 1 to 10
total = 0
for i in range(1, 11):
total += i
print("Sum =", total)
Output:
Sum = 55
6. Factorial of 5
n = 5
fact = 1
for i in range(1, n+1):
fact *= i
print("Factorial =", fact)
Output:
Factorial = 120
7. Multiplication table of 5
for i in range(1, 11):
print(f"5 x {i} = {5*i}")
Output:
5 x 1 = 5
5 x 2 = 10
...
5 x 10 = 50
8. Print each character in a string
for ch in "HELLO":
print(ch)
Output:
H
E
L
L
O
9. Reverse a string
s = "Python"
rev = ""
for ch in s:
rev = ch + rev
print("Reversed =", rev)
Output:
Reversed = nohtyP
10. Count digits in a number
num = 12345
count = 0
while num > 0:
num //= 10
count += 1
print("Digits =", count)
Output:
Digits = 5
11. Squares of first 5 numbers
for i in range(1, 6):
print(i, "squared is", i*i)
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
12. Cubes of first 5 numbers
for i in range(1, 6):
print(i, "cubed is", i**3)
Output:
1 cubed is 1
2 cubed is 8
3 cubed is 27
4 cubed is 64
5 cubed is 125
13. Fibonacci series (7 terms)
a, b = 0, 1
for _ in range(7):
print(a)
a, b = b, a+b
Output:
0
1
1
2
3
5
8
14. Print list elements
nums = [10, 20, 30, 40]
for n in nums:
print(n)
Output:
10
20
30
40
15. Largest number in list
nums = [12, 45, 23, 67, 34]
largest = nums[0]
for n in nums:
if n > largest:
largest = n
print("Largest =", largest)
Output:
Largest = 67
16. Numbers in reverse (10 to 1)
for i in range(10, 0, -1):
print(i)
Output:
10
9
8
...
1
17. Print only positive numbers
nums = [-3, -1, 0, 2, 5, -7, 8]
for n in nums:
if n > 0:
print(n)
Output:
2
5
8
18. Check prime number
n = 7
is_prime = True
for i in range(2, n):
if n % i == 0:
is_prime = False
break
print("Prime" if is_prime else "Not Prime")
Output:
Prime
19. Pattern printing (triangle)
for i in range(1, 6):
for j in range(1, i+1):
print("*", end=" ")
print()
Output:
*
* *
* * *
* * * *
* * * * *
20. Infinite loop with break
i = 1
while True:
print(i)
if i == 5:
break
i += 1
Output:
1
2
3
4
5