Python Programming - Loops - Discussion

Discussion Forum : Loops - General Questions (Q.No. 21)
21.
What does the else block in a for loop execute when the loop is terminated prematurely using a break statement?
It is executed when the loop condition is True.
It is executed when the loop is terminated prematurely.
It is executed only if an exception occurs in the loop.
It is executed when the loop completes its iterations normally.
Answer: Option
Explanation:

The else block in a for loop in Python has a specific behavior: it only executes when the loop completes all its iterations without encountering a break statement.

If a break statement is used to prematurely terminate the loop, the else block is skipped. This is because the break statement interrupts the normal flow of the loop, preventing it from reaching the end.

# Example
for number in range(10):
    if number == 5:
        break
    print(number)
else:
    print("The loop completed normally.")

In this example, the loop iterates from 0 to 9. When number reaches 5, the break statement is executed, and the loop terminates early. As a result, the else block is not executed.

Discussion:
Be the first person to comment on this question !

Post your comments here:

Your comments will be displayed after verification.