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?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:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers