Home Backend Development Python Tutorial The Strange &#else&# in Python

The Strange &#else&# in Python

Jan 03, 2025 am 03:32 AM

The Strange

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:

browser = get_browser()
if browser == 'chrome':
    driver = Chrome()
elif browser == 'firefox':
    driver = Firefox()
else:
    raise ValueError('Browser not supported')
Copy after login
Copy after login

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.

seasons = ['Winter', 'Spring', 'Summer', 'Autumn']
is_all_words_processed = True
for season in seasons:
    if not season.istitle():
        is_all_words_processed = False
        break
    print(season)

if is_all_words_processed:
    print('All seasons were processed')
Copy after login
Copy after login

Python allows us to avoid the additional variable by placing the logic when all words are valid into the else clause:

seasons = ['Winter', 'Spring', 'Summer', 'Autumn']
for season in seasons:
    if not season.istitle():
        break
    print(season)
else:
    print('All seasons were processed')
Copy after login
Copy after login

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:

seasons = ['Winter', 'Spring', 'Summer', 'Autumn']
index = 0
while index < len(seasons):
    if not seasons[index].istitle():
        break
    print(seasons[index])
    index += 1
else:
    print('All seasons were processed')
Copy after login
Copy after login

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).

file_name = 'input.dat'
try:
    f = open(file_name, 'r')
except FileNotFoundError:
    print('Incorrect file name')
else:
    for line in f:
        a, b = map(int, line.split())
        print(a / b)
    f.close()
Copy after login

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.

browser = get_browser()
if browser == 'chrome':
    driver = Chrome()
elif browser == 'firefox':
    driver = Firefox()
else:
    raise ValueError('Browser not supported')
Copy after login
Copy after login

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:
seasons = ['Winter', 'Spring', 'Summer', 'Autumn']
is_all_words_processed = True
for season in seasons:
    if not season.istitle():
        is_all_words_processed = False
        break
    print(season)

if is_all_words_processed:
    print('All seasons were processed')
Copy after login
Copy after login

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:

seasons = ['Winter', 'Spring', 'Summer', 'Autumn']
for season in seasons:
    if not season.istitle():
        break
    print(season)
else:
    print('All seasons were processed')
Copy after login
Copy after login

Now, let’s rewrite this method using else for both exception handling and loops:

  1. 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.
  2. 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.
  3. 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:

seasons = ['Winter', 'Spring', 'Summer', 'Autumn']
index = 0
while index < len(seasons):
    if not seasons[index].istitle():
        break
    print(seasons[index])
    index += 1
else:
    print('All seasons were processed')
Copy after login
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

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 by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

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

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

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 without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

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...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

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...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

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)...

See all articles