Full answer
python
def is_prime(n):
if n < 2:
return False
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
break
else:
return True
return False
def next_prime(n):
candidate = n + 1
while True:
if is_prime(candidate):
return candidate
candidate += 1
print([n for n in range(20) if is_prime(n)])
print(next_prime(90), next_prime(97))Output:
text
[2, 3, 5, 7, 11, 13, 17, 19]
97 101In is_prime, the else attached to the for runs only when no divisor triggered break, so it returns True for primes. Checking divisors up to the square root is enough, because any larger divisor pairs with a smaller one. next_prime keeps testing candidates in a while True loop and returns as soon as one is prime: 97 after 90 and 101 after 97. Many developers misread for-else, so a short comment or a helper function with an early return is often the clearer choice in team code.
python
def is_prime(n):
if n < 2:
return False
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
break
else:
return True
return False
def next_prime(n):
candidate = n + 1
while True:
if is_prime(candidate):
return candidate
candidate += 1
print([n for n in range(20) if is_prime(n)])
print(next_prime(90), next_prime(97))Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Loop else runs when no break happened
- Useful for search loops
- Check divisors up to the square root
- while True with return or break for open-ended loops
- Prefer clarity if the team finds for-else confusing
Common mistakes
- Thinking else runs when the loop body never executes only
- Checking every divisor up to n
Follow-ups
- How would you generate primes up to a million efficiently?
- How does break interact with try and finally?
Tips
- Explain when else runs