⚡ TechVani: AI, Technology, Apps, Coding & Digital World
TechVaniAI • Technology • Apps • Coding • Digital World
HomeAI & TechAppsCodingFree AI ToolsStudent TechSecurityAboutContactPrivacy
TECHVANI // LEARN. BUILD. TEST.

Learn the tech. Build the idea.

Clear study notes, tested lab files and practical guides for coding, AI and digital safety.

Explore Latest →
šŸ¤– AI & TechAI news, tools & guides šŸ“± Apps & ToolsUseful apps & websites šŸ’» CodingProgramming & web development šŸŽ“ Student TechStudy & career technology šŸ” Cyber SecuritySafety & awareness

Latest Posts

Circuit Notebook theme

Exam Notes

šŸ“š BTech CSE Exam Notes

Find Semester 1-8 subjects in one place. Choose a semester and open the notes you need. This is a general study guide, not an official syllabus.

Open Exam Notes →🧪 Open Lab Files →

Exam Numericals & Study Series

Practice CPU scheduling and explore OS and DBMS topics in separate, easy-to-follow parts. New topics will appear in the hub as they are published.

Open Numericals Hub →

Start here and stay in touch

New to TechVani? Start with our free AI tools guide for students. It covers which tools to try and what to check before relying on an answer.

For step-by-step videos, visit SiteSudhar on YouTube.

Join TechVani on WhatsApp

Get new AI tools and coding guides in your WhatsApp Updates tab.

Browse Topics

Popular Posts

TechVani

Python for-else and while-else Explained: break, continue and 7 Tested Examples

You search a revision list for Python. If it is present, stop searching. If it is absent, print a message only after every item has been checked. Python can express that last step with an else attached to a loop. It looks unusual because many beginners have only seen else attached to if.

This Proof Lab separates normal completion, break and continue through small programs. Run each block separately in Python 3. All shown outputs were executed and checked before publication.

1. What does loop else mean?

Definition: the else block of a for loop runs when its iterable is exhausted without a break. The else block of a while loop runs when its condition becomes false. A break in that loop skips its else. A return or an uncaught exception can also leave before else is reached.

The else is aligned with the loop, not with an if inside it. Indentation determines which statement owns the block. Read loop else as "the loop finished normally", not as "the condition inside if was false once".

2. A search flow you can trace

Loop starts / next check
             |
    Another item? (for)
    Condition true? (while)
       /              \
     No               Yes
      |                |
 Run loop else       Run body
      |                |
      |      +---------+---------+
      |      |         |         |
      |    break    continue   body ends
      |      |         |         |
      |   skip else    +----+----+
      |      |              |
      |      |        next loop check
      +------+----> after whole loop

return / exception leaving loop:
leave this path; else is not reached
The else path means normal completion. A break skips it. Return or an exception that leaves the loop exits this path instead.

3. Search succeeds: break skips else

topics = ["SQL", "Python", "OS"]
for topic in topics:
    print("check", topic)
    if topic == "Python":
        print("found")
        break
else:
    print("not found")
print("after loop")

Checked output:

check SQL
check Python
found
after loop

The loop checks SQL, then Python. The break exits this for loop. Its else block is skipped, but the statement after the loop still runs.

4. Search fails: exhaustion runs else

topics = ["SQL", "OS"]
for topic in topics:
    if topic == "Python":
        print("found")
        break
else:
    print("not found")

Checked output:

not found

Every item is checked and none matches. The iterable is exhausted without a break, so the else block reports the unsuccessful search. No separate found flag is needed.

5. An empty list still reaches else

for topic in []:
    print(topic)
else:
    print("no break occurred")

Checked output:

no break occurred

The body never starts, but the iterable is already exhausted. There was no break, so else runs. Loop else does not mean that the body must run at least once.

6. continue skips an iteration, not else

for number in [1, 2, 3]:
    if number == 2:
        continue
    print(number)
else:
    print("finished")

Checked output:

1
3
finished

continue skips the remaining body for number 2. It does not terminate the loop. After number 3 the loop is exhausted normally and else still runs.

7. while else follows a false condition

attempts = 0
while attempts < 3:
    attempts += 1
    print("attempt", attempts)
else:
    print("limit reached")

Checked output:

attempt 1
attempt 2
attempt 3
limit reached

The condition becomes false after the third attempt, so the else block runs. A break inside this while would skip it. Keep updates before any continue that could otherwise bypass them.

8. break belongs to the inner loop

for row in [1, 2]:
    for column in [1, 2]:
        print(row, column)
        break
    else:
        print("inner completed")
else:
    print("outer completed")

Checked output:

1 1
2 1
outer completed

Each inner loop breaks after its first column, so its else is skipped. The outer loop itself never breaks. It visits both rows and then runs its own else.

9. return leaves the function, not only the loop

def find_topic(topics):
    for topic in topics:
        if topic == "Python":
            return "found"
    else:
        return "not found"

print(find_topic(["Python", "OS"]))
print(find_topic(["SQL"]))

Checked output:

found
not found

A return exits the function immediately, so no later loop else is reached on the successful call. The second call exhausts the list and returns from else. In this function the final return could also be written after the loop; choose the clearer form for your team.

10. break, continue and normal completion compared

EventNext stepLoop else?
for has no items leftFinish the loop normallyYes
while condition is falseFinish the loop normallyYes
break in this loopLeave this loopNo
continueBegin the next iteration/checkNot skipped by continue alone
returnLeave the functionNot reached
Exception that leaves this loopTransfer control to an exception handlerNot reached

11. Boundary lab: six ways to leave or continue

Run this block separately. A caught exception inside the body does not by itself prevent normal completion. An exception that leaves the loop does. Compare the inner if else with the loop else by their indentation.

print('1. Initially false while:')
while False:
    print('body')
else:
    print('else without any iteration')
print('2. Exception caught inside the loop:')
for divisor in [0, 2]:
    try:
        print(10 // divisor)
    except ZeroDivisionError:
        print('caught; continue')
        continue
else:
    print('normal completion; else runs')
print('3. Exception leaves the loop:')
try:
    for divisor in [0, 2]:
        print(10 // divisor)
    else:
        print('loop else')
except ZeroDivisionError:
    print('caught outside; loop else was not reached')
print('4. False test inside the body is not completion:')
for number in [1, 2]:
    if number == 2:
        print('match')
        break
    else:
        print('if else: non-match')
else:
    print('loop else: no match')
print('5. A while break skips else:')
attempts = 0
while attempts < 3:
    attempts += 1
    if attempts == 2:
        print('found at', attempts)
        break
else:
    print('no result')
print('after while')
print('6. The continue-to-break practice:')
for number in [1, 2, 3]:
    if number == 2:
        break
    print(number)
else:
    print('finished')

Executed output:

1. Initially false while:
else without any iteration
2. Exception caught inside the loop:
caught; continue
5
normal completion; else runs
3. Exception leaves the loop:
caught outside; loop else was not reached
4. False test inside the body is not completion:
if else: non-match
match
5. A while break skips else:
found at 2
after while
6. The continue-to-break practice:
1

Trace the two search outcomes

Input/checkActionLoop stateElse?
SQL, then PythonCheck SQL; check Python; breakStops at PythonSkipped
SQL, then OSCheck both; request next itemIterator exhaustedRuns once
Empty listRequest first itemAlready exhaustedRuns once
Initially false whileTest conditionBody never enteredRuns once

Loop else is not a per-item failure branch. It belongs after the full sequence of checks. If the only goal is a Boolean membership test, "Python" in topics is often simpler. Use the loop when each item needs work or the search must stop at a richer condition.

12. Common exam mistakes

  • Printing "not found" inside the body after the first non-match. A later item may still match. Put the failure result after the complete search.
  • Indenting else under if instead of aligning it with for. Those are different programs.
  • Assuming any inner break skips every outer else. A break exits only the innermost enclosing loop.
  • Treating continue as break. Continue can still allow normal completion later.
  • Forgetting that an empty iterable or initially false while condition can run else immediately.

Use loop else when it makes a search or a retry result clearer. It is optional, not a badge of better Python. A named Boolean flag can be easier for a team unfamiliar with this syntax.

13. Exam questions with short answers

Q. When does for else execute?
When the iterable is exhausted without a break in that loop.

Q. Does an empty for loop run else?
Yes. Its iterable is already exhausted.

Q. Does continue skip loop else?
No. It skips the rest of one iteration, not the whole loop.

Q. Which loop does break terminate?
The innermost enclosing for or while loop.

Q. When does while else execute?
When the condition becomes false, including before the first iteration.

Q. How do you identify whether else belongs to if or for?
Check indentation: it aligns with the statement it belongs to.

Q. What does a return inside a loop do?
It exits the function, so the loop else is not reached.

Q. Does a caught exception always skip loop else?
No. If it is handled inside the body and the loop completes normally, else still runs.

Q. Is loop else the same as the else inside an if?
No. An if else can run for each non-match. A loop else runs once after normal completion.

Q. Does the statement after the whole loop run after break?
Yes, if nothing else transfers control away. Break skips the loop else, not the statement after the whole loop.

Try before checking

In the continue example, replace continue with break. Predict the output before running it. Answer: only 1 is printed. The loop breaks on 2, so neither 3 nor "finished" is printed.

Read next and sources

Comments