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.
Loop over [12, 25, 49, 50, 56] and print the first number divisible by 7, then stop. Output: First multiple of 7: 49.
Add up the positive numbers in [3, -1, 4, -5, 2], skipping negatives with continue. Print Total: 9.
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
What is the difference between break and continue?
When does the else block of a for loop run?
How do you search a list for a value using for/else, and why is that nicer than a flag?
Why can continue cause an infinite loop in a while loop?
Expected output
Dev is not in the list
29 is prime
21 is divisible by 3