For/Else and While/Else in Python: A Helpful Guide

The for/else and while/else statements are not syntax errors in Python. They have the following meaning:

The else branch executes if the loop terminates naturally: the loop condition is not met anymore.

The alternative is a “forced” termination from within the loop body using the “break” statement. In this case, the else branch does not execute.

Here’s an example code puzzle to test your understanding: can you already solve it based on what you know?

index = 5
string = 'g'

while index > 3:
    index -= 1
    if index == 3:
    string += 'o'

    string += 'd'


Solve the Python code puzzle on the Finxter app and track your progress.

Code Explanation

The integer variable “index” is initialized with the integer value 5. The string variable “string” is initialized with the character ‘g’.

Now, the while loop repeatedly appends the character ‘o’ to the string and decrements the index variable — until the index variable is smaller or equal the value 3. Roughly speaking, it executes the loop body two times for index=5 and index=4.

The interesting twist in the puzzle is that there is an “else” branch of the while loop! This is a nice little Python trick that is not very well known: the else branch is executed if the loop terminates because the loop condition is not met anymore. The alternative would be a “forced” termination of the loop from within the body using the “break” statement.

In other words: The else branch executes only if the loop runs over all elements in the loop sequence without leaving it early (via the “break” statement).

This is the case here (there is no break statement). In the last loop body execution, the index variable is decremented and takes value “3”. Thus, the interpreter executes the continue statement (just before appending the character ‘o’ once more) and goes to the loop condition to check whether it should execute it once more. This is not the case, so the program leaves the loop naturally and goes into the “else” branch where the character ‘d’ is appended to the string. The final result is, therefore:
‘g’ + ‘o’ + ‘d’ = ‘god’.

Leave a Comment

Your email address will not be published. Required fields are marked *