script_18.py - Break Statement Example
Code
#!/usr/bin/env python3
"""Break statement example - find first multiple"""
target = int(input("Find first multiple of: "))
limit = int(input("Search up to: "))
for i in range(1, limit + 1):
if i % target == 0:
print(f"First multiple of {target} is: {i}")
break
else:
print(f"No multiple of {target} found up to {limit}")
Explanation
Line 4-5: Variable assignments
- target is the number to find multiples of
- limit is upper bound for search
Line 7: for i in range(1, limit + 1):
- Searches from 1 to limit
Line 8: if i % target == 0:
- Checks if i is divisible by target
- % modulo returns 0 when evenly divisible
Line 10: break
- Exits the for loop immediately
- Jumps to code after the entire for/else block
- Only executes when first multiple found
- Stops searching once condition met
Line 11: else:
- Special for/else construct in Python
- else block attached to for loop (not common in other languages)
- Executes if loop completes normally (without break)
- Does NOT execute if break was called
- If break happens, else is skipped
- Used to detect "didn't find anything" scenario