Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 2.5 — break, continue and the Loop else
Python · Example 2 of 2

Searching with the loop else

Change wanted to "Ben" and watch the else block disappear. In the prime part, try 2, 1 and 49: what do you get for 1, and why? (The range is empty, so nothing breaks.)

break leaves a loop at once, continue skips the rest of the current pass, and the unusual else on a loop runs only when the loop finished without a break. Together they express searching and early exit cleanly.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Loop over [12, 25, 49, 50, 56] and print the first number divisible by 7, then stop. Output: First multiple of 7: 49.

02

Add up the positive numbers in [3, -1, 4, -5, 2], skipping negatives with continue. Print Total: 9.

03

Use for/else to check the password text "hello" for a digit (use letter.isdigit(), a text tool that gives True when letter is a digit; Phase 3 teaches such tools). Print No digit found if there is none.

Explain it without notes

01

What is the difference between break and continue?

02

When does the else block of a for loop run?

03

How do you search a list for a value using for/else, and why is that nicer than a flag?

04

Why can continue cause an infinite loop in a while loop?

Searching with the loop else
Sign in to run this example in your browser.

Expected output

Dev is not in the list
29 is prime
21 is divisible by 3