# Search with break
numbers = [4, 7, 2, 9, 1, 5]
target = 9
i = 0while i < len(numbers):
if numbers[i] == target:
print(f"Found {target} at index {i}")
break
i += 1else:
print(f"{target} not found")
# while-else runs only if loop completed without break
target = 99
i = 0while i < len(numbers):
if numbers[i] == target:
print(f"Found {target}")
break
i += 1else:
print(f"{target} not found")
Output
Click "Run" to execute your code
The else clause of a while loop runs only if the loop completed normally (without break). This is a clean pattern for search loops.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?