Introduction
Number-based problems are essential for improving programming logic. Using Python's while loop, we can solve different types of problems involving divisibility, counting, and special numbers.
This article demonstrates step-by-step solutions using simple logic and structured code.
Basic Practice
1. Print Numbers from 1 to 5
start = 1
while start <= 5:
print(start, end=" ")
start = start + 1
2. Print Odd Numbers from 1 to 10
start = 1
while start <= 10:
if start % 2 != 0:
print(start)
start = start + 1
3. Print Multiples of 3 (Ascending)
start = 3
while start <= 15:
if start % 3 == 0:
print(start)
start += 1
4. Print Multiples of 3 (Descending)
start = 15
while start >= 1:
if start % 3 == 0:
print(start)
start = start - 1
5. Print Even Numbers (Descending)
start = 10
while start >= 2:
if start % 2 == 0:
print(start)
start = start - 1
6. Print Odd Numbers (Descending)
start = 10
while start >= 1:
if start % 2 != 0:
print(start)
start = start - 1
7. Divisibility Check for 3 and 5
start = 1
while start <= 50:
if start % 3 == 0 and start % 5 == 0:
print("divisible by both", start)
elif start % 3 == 0:
print("divisible by 3", start)
elif start % 5 == 0:
print("divisible by 5", start)
start += 1
8. Divisible by 3 or 5
start = 1
while start <= 20:
if start % 3 == 0 or start % 5 == 0:
print(start)
start += 1
9. Finding Divisors of a Number
num = 12
i = 1
while i <= num:
if num % i == 0:
print(i)
i += 1
10. Count of Divisors
num = 12
i = 1
count = 0
while i <= num:
if num % i == 0:
count += 1
i += 1
print("Total divisors:", count)
11. Prime Number Check
num = 7
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")
12. Perfect Number Check
num = 6
i = 1
sum = 0
while i < num:
if num % i == 0:
sum += i
i += 1
if sum == num:
print("Perfect Number")
else:
print("Not a Perfect Number")
Explanation
- The
whileloop repeats execution until the condition becomes false - The
%operator is used to check divisibility - Logical operators like
andandorhelp combine conditions - Counters are used to track occurrences such as divisors
Top comments (0)