while — Intermediate Examples
Starts a loop that repeats as long as its condition is true
While with break and else
Using break to exit early and else for completion.
python
# Search with break numbers = [4, 7, 2, 9, 1, 5] target = 9 i = 0 while i < len(numbers): if numbers[i] == target: print(f"Found {target} at index {i}") break i += 1 else: print(f"{target} not found") # while-else runs only if loop completed without break target = 99 i = 0 while i < len(numbers): if numbers[i] == target: print(f"Found {target}") break i += 1 else: print(f"{target} not found")
Expected Output
Found 9 at index 3 99 not found
The else clause of a while loop runs only if the loop completed normally (without break). This is a clean pattern for search loops.
Want to try these examples interactively?
Open Intermediate Playground