Skip to the solution
EasyBackend5 min read

How do break, continue, pass and loop else work?

951 views

The problem

Question presented to candidate: "Walk me through break, continue and pass. Then tell me: Python loops can have an else clause β€” when does it run, and when would you actually use it?"

What a strong answer should cover:

  • break leaves the innermost loop immediately; continue skips the rest of the current iteration and goes back for the next item (or re-tests the while condition).
  • pass does nothing at run time; it only fills a place where the grammar needs a statement (empty function, class, or branch).
  • The loop else runs when the loop finishes without break β€” including a loop that runs zero times β€” and is skipped by break, return or an exception.
  • The idiomatic use: a search loop, where else means "not found", instead of a separate flag variable.
  • break only exits one loop level; to stop nested loops use a function with return, a flag, or the for-else-continue idiom. finally still runs when break leaves a try.

Code / implementation expected: Optional β€” a short search loop with for ... else, or a nested-loop exit.

  • control-flow
  • basics

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

Pythonbreak, continue and pass in one loop
PythonThe loop else clause: search, empty loops, while-else, primes
PythonLeaving nested loops, and break with finally

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 10 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

What is the difference between a module and a package?

Continue