← All lessons

else in loops

Sign in · Sign up

Lesson 3.5

A loop can have an else too. It runs if the loop reached the end without being stopped by break:

word = "cat"

for letter in word:
    if letter == "z":
        print("The word has a z")
        break
else:
    print("There is no z")

It reads like this: "if we found it, we said so and left; if we reached the end without leaving, then we never found it". Don't copy the example: the task looks for a divisor of a number, not a letter.

Two rules for writing it:

  • else sits at the same level as for, not inside the body;
  • without a break in the loop, else always runs, and it makes no sense.

Check whether the number number has divisors from 2 to number - 1: if it does, print Not prime and break out of the loop. If it has none — print Prime. number is set by the check.

Hint

The else of a for runs only if the loop was not stopped by break.

Inside the loop we look for a divisor: if we find one, we print "not prime" and leave. If the loop reaches the end, the else runs with the "prime" message.