Python Loop else · Exercises
Beginner

Python Loop else Exercises

4 exercises that build on the Python else on Loops lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: The else block of a for or while loop runs once when the loop finishes normally, and is skipped when a break ends the loop. By the end you can write the search pattern with for ... else, check for primes, use else on a while loop, tell a loop's else from an if's else, and know when a flag is clearer. You will practise: Is the username free?; Predict the else; Fix the receipt search; Collect the primes up to 30.

0 / 4 completed

Python Loop else practice exercises

1. Is the username free?

Write code Easy

Loop over taken. If a name equals wanted, print <name> is taken and break. If the loop finishes without a break, print <name> is available using an else block on the loop. With the starting data the output is a single line: dina is available.

Your code
taken = ["asha", "ben", "chen"]
wanted = "dina"

# for ... else here

2. Predict the else

Predict the output Medium

Read the code and type exactly what it will print. Then press Check to run it and compare.

Read this code
count = 0
while count < 5:
    count += 1
    if count == 2:
        continue
    if count == 7:
        break
    print("count", count)
else:
    print("else ran")
print("end", count)

4. Collect the primes up to 30

Write code Hard

Build the list of prime numbers from 2 up to and including limit in primes, then print it. For every candidate, try each divisor from 2 up to the candidate minus 1 in an inner loop: break as soon as one divides evenly, and use the inner loop's else to append the candidate when none did.

Your code
limit = 30
primes = []

# for each number from 2 to limit, try the divisors in an inner loop
# break on a match; use else to add the prime to the list

Next lessonPython Nested Loops

More Python else on Loops examples · All Python exercises