for else Runs When No Break Fired
The else clause attached to a for loop runs only when no break fired, turning a search miss into structured control flow.
Code
def find_first_even(numbers):
for n in numbers:
if n % 2 == 0:
return n
else:
# else runs only when the loop finished without break or return
return None
print(find_first_even([1, 3, 5]))
print(find_first_even([1, 4, 5]))
# The common pattern: search with a break, else handles the miss
for user in ["ana", "bo", "cy"]:
if user == "bo":
print("found:", user)
break
else:
print("no bo found")
for user in ["ana", "cy"]:
if user == "bo":
print("found:", user)
break
else:
print("no bo found")Output
Captured from a sandboxed run of this snippet in the build pipeline.
None
4
found: bo
no bo foundInside the snippet
Everything that executes sits inside the function find_first_even.
The cycling part of this snippet is for n in numbers.
What to watch for
- Nothing sits in the dependency list; the runtime itself supplies it all.
Using it
The signature doing the main work is def find_first_even(numbers)
Look for the found:, no bo found prefixes during the file’s run; they match each line of output to the step that emitted it.
The surface worth importing is find_first_even; the helpers around it are private to the snippet.
Key statements
def find_first_even(numbers):
for n in numbers:
if n % 2 == 0:
return n
else:
# else runs only when the loop finished without break or return
return None
Interactive Tools for This Topic
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. The file defines `find_first_even` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.