Learn to Use 3 Other “Else” Clauses in Python
Some lesser-known features of Python
Introduction
Anyone with any programming experience should be familiar with the if…else statement. Basically, it creates a logical branch by examining a particular condition. When the condition is evaluated to be true, the program will execute the operations in the if clause, otherwise executing those in the else clause. Notably, the code in these two clauses will be mutually exclusive, which means that when the code in the if clause gets executed, the code in the else clause will be skipped altogether and vice versa.
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
We know that iteration is one of the most common operations that we do in the program as an important way to enable automation. Specifically, we mostly use the for loop, and perform particular actions by going over some sort of iterables, such as lists, dictionaries, sets, and many others. The most basic format is shown below.
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.
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
The while statement is particularly useful when a condition is subject to change at a later time during execution. Specifically, while the condition is true, the code in the while cause will execute until the condition becomes false. Let’s see an example first.
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.
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
Exception handling is a tricky task in coding. When you don’t do it, your program is very fragile. However, if you do it too much, the readability of your code is severely reduced. Thus, you need to find a balance for how much and when you need to handle exceptions. Certainly, the current article isn’t about handling exceptions in Python. Instead, let’s just talk about the feature of exception handling. Specifically, we will use the try…except statement to handle an exception in Python. Let’s see an example:
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.
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
In this article, we reviewed three other else clauses besides the most well-known usage of else clause in the if statement. Here’s a quick recap of these three usages.
- When the
elseclause is used in theforandwhilestatement, the code in theelseclause won’t execute if the preceding clause (fororwhile) encounters abreakstatement. Otherwise, it will execute following the preceding clause. - When the
elseclause is used in thetry…exceptstatement, the code in theelseclause won’t execute if any exception is raised during the execution of thetryclause. It will only run when thetryclause 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!
'Data Analytics(en)' 카테고리의 다른 글
| Don’t Choose Python as Your First Programming Language (0) | 2020.10.17 |
|---|---|
| Visual Studio Code for Data Science — the Power User’s guide (0) | 2020.10.16 |
| Create a template for your Jupyter Notebooks (0) | 2020.10.14 |
| Elon Musk’s 2 Rules For Learning Anything Faster (0) | 2020.10.13 |
| How To Make Money Using Web Scraping (0) | 2020.10.12 |