In Python, the for-else and while-else loops incorporate an else clause that is somewhat unconventional when compared to similar constructs in other programming languages. This else clause executes only after the loop finishes its normal execution—meaning it runs to completion without being interrupted by a break statement.
This feature is particularly useful for scenarios where you need to confirm that a process was completed as expected without early termination.
Python - for-else Loop
The for-else loop is useful for situations where you need to process all items in a sequence and then perform some final action if and only if the entire sequence was processed. This is commonly used in search operations where the absence of a break statement can signify that an item was not found.
Syntax
- for item in iterable: This initiates the loop. The loop variable
itemtakes each value from theiterableone by one. - else: This keyword introduces a block that only executes if the loop exhausts the iterable without encountering a
breakstatement.
Execution Flow
Image scaled to 60%
Basic Example without break
Explanation:
- Loop Iteration: The loop iterates over each element in the
numberslist and prints it. - Else Execution: Since there is no
breakstatement interrupting the loop, theelseclause executes right after the loop finishes, indicating that all numbers have been processed.
Example with break
Explanation:
- Condition Check: The loop checks each number to see if it is
3. - break Execution: When it finds
3, it prints a message and executes abreak, stopping the loop. - Else Non-execution: Because the loop was interrupted by the
break, theelseclause does not execute.
Python - while-else Loop
The while-else loop is ideal for performing a task repeatedly under a condition and executing an action afterwards if the loop wasn’t prematurely stopped by a break.
Syntax
- while condition: This line sets the condition for the loop to run. As long as the condition evaluates to True, the loop continues to execute.
- else: Similar to the
for-elsestructure, this part of the loop runs only if thewhileloop completes by the condition turning False and not if the loop is exited via abreakstatement.
Example with break
Explanation:
- Interrupt Condition: If
countreaches 2, the loop prints a message and breaks. - Else Non-execution: Since the loop is interrupted by the
break, theelseblock does not execute, signaling that the loop did not finish naturally.
These examples clearly illustrate how the else clause in Python loops adds a layer of logic that can handle both complete and interrupted loop executions. This functionality provides a powerful tool for managing loop outcomes based on whether they were able to run to completion.