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.
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)
The integer variable
index is initialized with the integer value 5. The string variable
string is initialized with the character
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
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.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.