🔁 Learn advanced looping techniques in Python, including the for...else and while...else constructs, and how to emulate the classic do...while loop using standard Python syntax.
This section is designed to help you write more expressive and robust loops by understanding how to control execution flow beyond basic iteration.
- ✅ How to use
for...elseandwhile...elsestatements - 🔁 How to emulate a
do...whileloop in Python - 📌 Use cases and best practices for each construct
- 💡 Hidden tips and notes that improve readability and avoid common mistakes
Python allows the else clause to be used with the for loop — this is not available in most other programming languages.
🔹 Syntax:
for item in iterable:
# code to process item
if condition:
break
else:
# code to run if loop completes normally (no break)🔸 The else block runs only if the loop completes all iterations without encountering a break statement.
fruits = ['apple', 'banana', 'cherry']
search = 'mango'
for fruit in fruits:
if fruit == search:
print(f"Found {search}!")
break
else:
print(f"{search} not found.")🔹 Use Cases:
- Searching for an item in a collection
- Validating input or data before proceeding
- Checking conditions across an entire sequence
Just like for, the while loop can also have an else clause.
🔹 Syntax:
while condition:
# code to execute while condition is True
if some_condition:
break
else:
# code to run if loop exits because condition became False🔸 The else block runs if the loop exited due to the condition becoming False, not from a break.
attempts = 0
max_attempts = 3
while attempts < max_attempts:
password = input("Enter password: ")
if password == "secret":
print("Login successful!")
break
print("Incorrect password.")
attempts += 1
else:
print("Account locked due to too many failed attempts.")🔹 Use Cases:
- Retry logic with limits
- Game loops
- Input validation with retries
Unlike languages like Java or C++, Python does not have a built-in do...while loop, but you can emulate it using a while loop with a break.
🔹 Concept:
The do...while loop executes the body at least once, then checks the condition at the end of each iteration.
import random
MIN, MAX = 1, 10
secret_number = random.randint(MIN, MAX)
while True:
guess = int(input(f"Guess a number between {MIN} and {MAX}: "))
if guess > secret_number:
print("Too high. Try again.")
elif guess < secret_number:
print("Too low. Try again.")
else:
print("Bingo! You guessed it!")
break🔹 This pattern ensures the user makes at least one guess before checking whether to continue.
- Use
while Trueto simulate the “do” part. - Add a
breakwhen the exit condition is met. - Ideal for scenarios where the loop must run at least once.
| Construct | Use Case |
|---|---|
for...else |
Search algorithms, validation, checking all elements |
while...else |
Game loops, retry logic, login systems |
do...while emulation |
Prompting users, input validation, menu loops |
🧠 Hidden Details & Notes
- 🔁 The
elseblock in bothforandwhileloops runs only when the loop completes naturally — not when interrupted bybreak,return, or exceptions. - ❗ Avoid putting complex logic inside the
elseblock unless necessary — it can reduce readability. - 🧪 The
elseclause is often misunderstood and underused — but very useful in scenarios where you want to handle a “none found” or “loop completed” case. - 🚫 Using
continuedoes not affect theelseclause — onlybreakdoes. - 🧹 Always test edge cases — especially when working with empty iterables in
for...else.
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
print(f"{n} is divisible by {i}. Not a prime.")
break
else:
print(f"{n} is a prime number.")
return True
return False
is_prime(17)🎉 Congratulations! You now have a solid understanding of advanced loop structures in Python, including how to use for...else, while...else, and emulate do...while behavior.
Next up: 📦 Section 10: More on Python Functions – learn about unpacking tuples, variable arguments (*args, **kwargs), partial functions, and type hints.