Python’s while loop is a powerful control structure that repeatedly executes code as long as a specified condition remains true. Unlike for loops, it continues running until an explicit termination condition is met—making it perfect for problems that require dynamic counting, divisibility checks, and number generation.
This guide walks through 12 practical Python examples using while, each designed to strengthen your understanding of loops, conditionals, and number theory. Whether you're preparing for technical interviews or just sharpening your coding skills, these exercises will help you write cleaner, more logical code.
Simple Number Sequences: From Basic Counting to Patterns
The while loop excels at printing sequences in both ascending and descending order. It’s ideal for tasks like listing numbers, filtering odd or even values, and generating multiples.
- Count from 1 to 5: Start at
1and increment until the counter exceeds5. - Print odd numbers up to 10: Use the modulus operator (
%) to check if a number is not divisible by2. - Generate multiples of 3 in ascending order: Begin at
3and add3repeatedly until the value exceeds15. - List multiples of 3 in reverse: Start at
15and subtract3until reaching0.
These examples demonstrate how small changes in initialization and increment logic can drastically alter output direction and purpose.
Divisibility and Filtering: Logic with Conditions
Real-world programming often requires filtering data based on divisibility rules. The while loop, combined with if statements, allows precise control over which numbers are processed.
For instance, to identify numbers between 1 and 20 divisible by either 3 or 5:
start = 1
while start <= 20:
if start % 3 == 0 or start % 5 == 0:
print(start)
start += 1More complex logic emerges when checking divisibility by multiple factors. To detect numbers divisible by both 3 and 5 (e.g., 15, 30, 45):
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 += 1This nested conditional structure shows how multiple conditions can coexist within a single loop, enabling nuanced output.
Exploring Number Properties: Divisors, Primes, and Perfection
Beyond filtering, while loops are indispensable for analyzing number properties—such as identifying divisors, confirming primality, or verifying perfect numbers.
- List all divisors of 12: Iterate from
1to12and print each number that divides12without a remainder.
num = 12
i = 1
while i <= num:
if num % i == 0:
print(i)
i += 1- Count total divisors: Maintain a counter variable to tally divisors as they’re found.
num = 12
i = 1
count = 0
while i <= num:
if num % i == 0:
count += 1
i += 1
print("Total divisors:", count)- Check if a number is prime: A prime has exactly two divisors:
1and itself. Count divisors to verify.
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")- Identify perfect numbers: A perfect number equals the sum of its proper divisors (excluding itself). For example,
6 = 1 + 2 + 3.
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")Key Takeaways: Writing Clean, Maintainable Loops
The power of the while loop lies in its flexibility. By adjusting the loop condition, increment logic, and conditional checks, you can solve a wide range of problems—from simple counters to complex mathematical validations.
- Use clear variable names like
start,count, orsumto improve readability. - Keep updates (e.g.,
start += 1) inside the loop body to prevent infinite execution. - Combine
whilewithif,elif, andelseto create layered logic. - Leverage the modulus operator (
%) for divisibility and remainder checks.
Practice these examples, modify them, and experiment with edge cases. As your comfort grows, the while loop will become a go-to tool for handling iterative logic in Python.
Python loops are foundational. Mastering them today will make advanced algorithms, data processing, and even AI model training far more intuitive tomorrow.
AI summary
Python while döngüsüyle sayı dizileri oluşturun, asal sayıları tespit edin ve mükemmel sayıları bulun. Temelden ileri seviyeye algoritma geliştirme rehberi.