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 because the loop condition isn’t met anymore. You may ask: isn’t this always the case? No! You can also have a “forced” termination from within the loop body using the “break” statement. In this case, the else branch does not execute.
Based on the last paragraph, have a look at the interactive code shell and try to modify the code such that the else branch is not executed:
Have a look at the program flow of the normal (for or while) loop and compare it to the program flow with the for/else and while/else loop. What’s the difference?
The blue box indicates that the else branch executes only if the loop is left via the “False” branch, not via the “Break” branch.
Code Puzzle
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: continue string += 'o' else: string += 'd' print(string)
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'
.
Where to Go From Here
If you keep struggling with those basic Python commands and you feel stuck in your learning progress, Iβve got something for you: Python One-Liners (Amazon Link).
In the book, Iβll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basicsβall in a single line of Python code!
OFFICIAL BOOK DESCRIPTION: Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation.