Learn to Use 3 Other “Else” Clauses in Python

Some lesser-known features of Python

Yong Cui, Ph.D.
Jul 24 · 5 min read
Image for post
Image for post
Photo by Tolga Ulkan on Unsplash

Introduction

Between different languages, there are variations in syntactical details. For example, Kotlin requires that you use parentheses for the condition evaluations, while parentheses are optional in Swift and Python. Both Kotlin and Swift use curly braces for each if and else clauses, but Python uses colons and indentations to denote the scope. Other languages have some other variances, but nothing is surprising to tech-savvy outsiders who are not experts in these particular languages.

In most of these languages, the if and else clauses only exist in the if…else statement, and they don’t appear anywhere else in the language. However, Python is unusual in this regard, because there are three other usages of the else clauses. In this article, we’ll review what they are and how we can use them with some realistic examples.

The “for” Statement

Basic Form of “for” Loop

We can append an else clause following the for loop. At what condition does the else clause get executed? Here’s the rule.

The code in the else clause will execute only when the for loop completes all the iterations. If the for loop is prematurely stopped by a break statement, the else clause will be skipped too.

Sounds confusing? Sure, is. The else clause is indeed tricky when it’s outside the context of the if…else statement. Let’s understand this usage with a simple code example.

“For…else” Statement

As shown above, when the ordered items are are available, the else clause gets executed, showing that the group order is possible. When any item is found to be unavailable, the execution will run into the break statement (Line 6), which will result in the skip of the else clause.

The “while” Statement

“While” Statement

As shown above, the code in the while clause continues to execute until the saving balance isn’t greater than zero. As indicated by the subsection title, we can also have an else clause with the while statement. Here’s the rule:

The code in the else clause will execute only when the while loop exits normally because the condition evaluates false. If the while loop is prematurely stopped by a break statement, the else clause will be skipped too.

I know that it’s confusing as well. It’s better understood through a more realistic example. I’ll just simply append the else clause to the above example with a few tweaks.

“While…else” Statement

As shown above, we now set an alert level, below which, we’ll stop the withdrawal activities by executing the break statement. As you can see, when the alert level is set to 100, the while loop exits normally because the final balance reaches zero. However, when the alert level is set to 500, after the third withdrawal, the balance becomes 400, which will trigger the code execution in the if statement, and thus the break statement will make the while loop stop execution prematurely, by doing which, the else clause won’t execute.

The “try” Statement

Basic Form of the “try…except” Statement

As shown above, we simply try to cast a string to an integer. When a string is able to be cast, all of the code in the try clause executes. However, when we cast a string that isn’t integer compatible, the exception is raised and handled by the code in the except clause. Pretty straightforward exception handling, right? Since this article is talking about else clauses, you can bet that we can also use an else clause in the try…except statement, and you’re absolutely right about that. Let’s see the rule:

The code in the else clause will execute only when the try clause completes normally without encountering any exceptions.

This is probably the easiest one to understand among these three else clause usages. Nevertheless, consider the following code for its specific usage.

“Try…except…else” Statement

In the above code, we move the print function that was originally in the try clause to the else clause. For these two function calls, as you can see, the else clause executes only when there is no ValueError exception raised, consistent with its intended usage.

Notably, minimizing the code in the try clause is significant, because it will inform us exactly of what code can cause exceptions, in which case, it’s the int() function. Thus, the else clause has added benefits in making our code cleaner compared to the previous two usages.

Conclusions

  • When the else clause is used in the for and while statement, the code in the else clause won’t execute if the preceding clause (for or while) encounters a break statement. Otherwise, it will execute following the preceding clause.
  • When the else clause is used in the try…except statement, the code in the else clause won’t execute if any exception is raised during the execution of the try clause. It will only run when the try clause raises no exceptions.

Among these three, people may be the most familiar with the else clause in the try…except statement. Regarding the other two, they can be very confusing to new Python coders. Even for those more seasoned ones, if you don’t use these under appreciated features, they can still be confusing. Thus, my advice is to know these features, which will allow you to read others’ code who may happen to use them. If you’re using these features yourself, you may want to make sure that your code readers (e.g., in a team project) can appreciate these features, too.

Thanks for reading!

Better Programming

Advice for programmers.

Thanks to Zack Shapiro

Yong Cui, Ph.D.

Written by

Work at the nexus of biomedicine, data science & mobile dev. Love to write on these technological topics. Follow me @ycui01 on Twitter to get latest articles.

Better Programming

Advice for programmers.

Yong Cui, Ph.D.

Written by

Work at the nexus of biomedicine, data science & mobile dev. Love to write on these technological topics. Follow me @ycui01 on Twitter to get latest articles.

Better Programming

Advice for programmers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store