Python

Beyond If-Else: Leveraging Python’s Versatile “Else” Statements

3 unexpected but practical usages

Yang Zhou
TechToFreedom
Published in
3 min readMar 20, 2024

--

3 practical usages of else statements of Python
Image from Wallhaven

When it comes to “else”, there must be an “if” first.

This is correct for many programming languages, but not for Python.

The else statements of Python are more versatile than we think.

From an “else” after a loop to an “else” following a try-except block, this article will explore the lesser-known capabilities of the else statements.

It’s not necessarily that we need to use these tricks in production, especially when our colleagues don’t know them yet, but merely being aware of their existence can make us feel the flexibility and versatility of Python again.

1. While-Else Structure

In Python, a while loop can be paired with an else block. The else block will execute if and only if the loop completes normally, meaning it didn't terminate through a break statement.

In other words, if a while loop was terminated by a break, the else block would not be executed.

leaders = ["Elon", "Tim", "Warren"]
i = 0
while i < len(leaders):
if leaders[i] == "Yang":
print("Yang is a leader!")
break
i += 1
else…

--

--