I’ve been asked by a few people recently to explain the different uses for the else
keyword in python.
python, for a reasons I do not understand, decided to overload the else
keyword in ways most people never think of.
The spec isn’t too friendly to beginners either. This is a partial piece of the python grammar specification, for symbols that accept the else
keyword, as it is read by the parser generator and used to parse Python source files:
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] |
That’s kind of cryptic, right?
This blog post is primarily aimed at beginners, and covers:
The post has no ordering. You can pick-n-choose the ones you’re not familiar with.
if … else [ one liner ]
<value> if <condition> else <value if condition is False> |
for example, instead of writing this:
age = 27 |
we can do the same in one line:
age = 27 |
for | while … else
for
and while
loops take an optional else suite, which executes if the loop iteration completes normally. In other words, the else
block will be executed only if no break
& return
were used, and no exception has been raised.
for <value> in <iterable>: |
The following code randomizes five numbers, and prints them if they are not divisible by three. If that was the case for all of the numbers, it also print a message saying so.
from random import randint |
what is ‘for..else’ good for?
A common use case is to implement search loops:
condition_is_met = False |
Using the else
keyword, we can cut a few lines. It makes the code slimmer and more concise. I like it.
for value in data: |
Because many people aren’t aware of the for...else
syntax, I usually add a comment that explains when the else
block is executed.
what is ‘while…else’ good for?
Lets recap on the syntax first -
while <condition>: |
A common skeleton for code processing code:
|
Again, we can remove the flag by leveraging the else
keyword:
while value < threshold: |
try-catch-else-finally
try-catch-finally
take an optional else suite, which executes if no exception were raised inside the try block -
try: |
what is it good for?
The following code is, unfortunately, common-place:
no_error = False |
Adding a flag at the end of the try
block is weird and non pythonic in my opinion. The else
keyword really shines here and makes the code more readable:
try: |