3.3.3 The Loop Else Clause

Unit: Unit 3: Loops • Interactive Practice

Quick Answer & Summary:

Interactive Python programming tutorial and practice in your browser.

Interactive Challenge (Run Live in Browser):

# Search for a prime number or confirm primality using for-else
candidate = 7

for divisor in range(2, candidate):
    if candidate % divisor == 0:
        print(candidate, "is composite (divisible by", divisor, ")")
        break
else:
    # Executes ONLY if the loop completed naturally without hitting break!
    print(candidate, "is a prime number!")
Open in Live Interactive Python Sandbox →