The Strange &#else&# in Python
Else in Conditional Statements
We’ve all written conditional statements and have probably used the complete if-elif-else structure at least once.
For example, when creating a web driver instance for the required browser:
1 2 3 4 5 6 7 |
|
This snippet supports testing with Chrome and Firefox, and raises an exception if an unsupported browser is provided.
A lesser-known fact is that Python supports the use of the else clause with loops and exception handling.
Else with Loops
Imagine we have a list of words, and we want to print them as long as they start with an uppercase letter. At the end, we want to check whether all words were processed and, if so, perform specific logic.
We might use a flag variable is_all_words_processed, setting it to False if we encounter an invalid word, then checking it outside the loop to execute the logic.
1 2 3 4 5 6 7 8 9 10 |
|
Python allows us to avoid the additional variable by placing the logic when all words are valid into the else clause:
1 2 3 4 5 6 7 |
|
The else block will execute only if the loop completes naturally, without a break. If the loop is interrupted by break, the else clause will not run.
Here’s the same example rewritten with a while loop. With while, the else clause behaves in the same way:
1 2 3 4 5 6 7 8 9 |
|
Else in Exception Handling
The else clause can also be used in exception handling. It must come after all except blocks. The code inside the else block will execute only if no exceptions are raised in the try block.
For example, let’s read a file containing numbers in two columns and print their quotient. We need to handle an invalid file name, while any other errors (e.g., converting a value to a number or division by zero) should cause the program to crash (we will not handle them).
1 2 3 4 5 6 7 8 9 10 |
|
In this example, the try block contains only the code that might raise the caught exception.
The official documentation suggests using the else block to avoid unintentionally catching exceptions raised by code outside the try block. Still, the use of else in exception handling might not feel intuitive.
Combining Else with Loops and Exception Handling
Here’s an question I posed at interviews.
Suppose we have a Driver class with a method find_element. The find_element method either returns an element or raises an ElementNotFoundException exception. In this example, it’s implemented to randomly return an element or raise an exception with equal probability.
Using basic Python syntax, implement a method smart_wait(self, locator: str, timeout: float, step: float) that checks for an element with the given locator every step seconds. If the element is found within timeout seconds, return; otherwise, raise an ElementNotFoundException exception.
1 2 3 4 5 6 7 |
|
Here’s one approach to implement this method:
- Trying to find the element as long as the timeout hasn't elapsed.
- If the element is found, exit the loop.
- If the element isn’t found, wait for the step interval.
- Raise an ElementNotFoundException if the timeout is exceeded. Here’s a straightforward implementation:
1 2 3 4 5 6 7 8 9 10 |
|
We could shorten the logic a bit by using return instead of break, but let's leave it as i for now.
In fact, this method is implemented in the WebDriverWait class of Selenium - until method:
1 2 3 4 5 6 7 |
|
Now, let’s rewrite this method using else for both exception handling and loops:
- Exception could be raised only in line self.find_element(locator). Exit from loop should be performed in case when exception wasn't raised. So we could move break to else block.
- Our method should raise exception if loop was exited not because of break. So we could move exception raising to else clause of the loop.
- If you perform transformation 1 and 2 consequentially, you see that current time could be taken only in loop condition.
Completing these transformations, we obtain a method that uses the else statement for both exception handling and the loop:
1 2 3 4 5 6 7 8 9 |
|
What can I say... This is one of Python’s lesser-known features. Infrequent use might make it less intuitive to use in every scenario — it can lead to confusion. However, knowing it and applying it effectively when needed is undoubtedly worthwhile.
Happy New Year! ???
P.S. It was really scary ?:
I write articles on my own but translate them using ChatGPT. For translation I removed all code snippets but ChatGPT restores them all ?
The above is the detailed content of The Strange &#else&# in Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

Fastapi ...

Using python in Linux terminal...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...
