Python's while loop allows a block of code to execute repeatedly as long as a condition is true. It is one of the first looping concepts every beginner should learn.
In this article, we'll explore practical examples using while loops.
1. Print 1 Five Times
count = 1
while count <= 5:
print(1, end=" ")
count += 1
Output
1 1 1 1 1
2. Print Numbers from 1 to 5
count = 1
while count <= 5:
print(count, end=" ")
count += 1
Output
1 2 3 4 5
3. Print Odd Numbers
count = 1
while count < 10:
print(count, end=" ")
count += 2
Output
1 3 5 7 9
4. Print Multiples of 3
count = 3
while count <= 15:
print(count, end=" ")
count += 3
Output
3 6 9 12 15
4(i). Print Multiples of 3 in Reverse
count = 15
while count >= 3:
print(count, end=" ")
count -= 3
Output
15 12 9 6 3
4(ii). Print Even Numbers in Reverse
count = 10
while count >= 2:
print(count, end=" ")
count -= 2
Output
10 8 6 4 2
4(iii). Print Odd Numbers in Reverse
count = 9
while count >= 1:
print(count, end=" ")
count -= 2
Output
9 7 5 3 1
5. Multiples of 3 and 5 ?
num = 1
while num <= 30:
if num % 3 == 0 and num % 5 == 0:
print(num)
num += 1
Output
15
30
6. Multiples of 3 or 5
num = 1
while num <= 30:
if num % 3 == 0 or num % 5 == 0:
print(num)
num += 1
7. Divisors of a Given Number
num = int(input("Enter a number: "))
i = 1
while i <= num:
if num % i == 0:
print(i)
i += 1
Example
Input: 12
Output: 1 2 3 4 6 12
8. Count of Divisors
num = int(input("Enter a number: "))
i = 1
count = 0
while i <= num:
if num % i == 0:
count += 1
i += 1
print("Number of Divisors:", count)
9. Prime Number Check
num = int(input("Enter a number: "))
i = 1
count = 0
while i <= num:
if num % i == 0:
count += 1
i += 1
if count == 2:
print("Prime Number")
else:
print("Not a Prime Number")
10. Perfect Number Check
num = int(input("Enter a number: "))
i = 1
sum_div = 0
while i < num:
if num % i == 0:
sum_div += i
i += 1
if sum_div == num:
print("Perfect Number")
else:
print("Not a Perfect Number")
Example
6 = 1 + 2 + 3
11. Print 1 3 5 7 9 2 4 6 8 10 Using a Single Loop
i = 1
while i <= 10:
if i <= 5:
print(2 * i - 1, end=" ")
else:
print(2 * (i - 5), end=" ")
i += 1
Output
1 3 5 7 9 2 4 6 8 10
12. Factorial of N Number
num = int(input("Enter a number: "))
fact = 1
i = 1
while i <= num:
fact *= i
i += 1
print("Factorial =", fact)
Example
5! = 120
13. Sum of First n Numbers
n = int(input("Enter a number: "))
sum = 0
i = 1
while i <= n:
sum += i
i += 1
print("Sum =", sum)
Example
1 + 2 + 3 + 4 + 5 = 15
14. Print First 5 Prime Numbers
count = 0
n = 2
while count < 5:
i = 1
divisors = 0
while i <= n:
if n % i == 0:
divisors += 1
i += 1
if divisors == 2:
print(n, end=" ")
count += 1
n += 1
Output
2 3 5 7 11
15. Sum of First 5 Prime Numbers
count = 0
n = 2
total = 0
while count < 5:
i = 1
divisors = 0
while i <= n:
if n % i == 0:
divisors += 1
i += 1
if divisors == 2:
total += n
count += 1
n += 1
print("Sum of first 5 prime numbers:", total)
Output
Sum of first 5 prime numbers: 28

Top comments (0)