# for/else: check if a number is primedefis_prime(n):
if n < 2:
returnFalsefor i inrange(2, int(n**0.5) + 1):
if n % i == 0:
returnFalse# could use break + else here tooreturnTrue# Using for/else patternfor n in [17, 18, 19, 20]:
for i inrange(2, n):
if n % i == 0:
print(f"{n} = {i} x {n//i}")
breakelse:
print(f"{n} is prime")
Output
Click "Run" to execute your code
Loop else is unusual: it runs when the loop finishes normally (without break). Think of it as 'nobreak' — it runs if break was never hit.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?