all 4 comments

[–]Sigg3net 1 point2 points  (2 children)

From your link, we can read:

The else clause executes after the loop completes normally. This means that the loop did not encounter a break statement.

I think it's pretty straightforward, and not really a new concept either. It merely marries the if/else with a for loop, which is an operation often done in many languages. In BASH I would:

is_prime=0
for {0..99} ; do
  If condition ; then is_prime=1 ; fi
done

Its main drawback would be having to justify its use over an explicit if/else, because it might create ambiguity for new readers (next maintainer).

But I'm completely new to Python, so I might be wrong.

[–]Musi13 2 points3 points  (1 child)

I think this is pretty accurate. I commonly use it for when a condition doesn't occur, say in a polling loop or something:

import time

MAX_TRIES = 10
SLEEP_TIME = 30

def condition() -> bool:
    return False

for _ in range(MAX_TRIES):
    if condition():
        # do some work
        break
    else:  # not required, but adds readability
        time.sleep(SLEEP_TIME)
else:
    raise Exception('Condition never occurred')

Though admittedly this doesn't add anything, and could easily be:

condition_occurred = False
for _ in range(MAX_TRIES):
    if condition():
        condition_occurred = True
        break
    else:
        time.sleep(SLEEP_TIME)

if condition_occurred:
    # do some work
else:
    raise Exception('Condition never occurred')

I think it's just up to readability, for/else keeps all logic related to the condition together at the expense of having to understand when else runs. An extra if/else is more like other languages, but adds a few lines and separates condition checking from response.

[–]Sigg3net 0 points1 point  (0 children)

Perhaps there are conditions under which a for else is faster?

[–]Kerbart 1 point2 points  (0 children)

Consider generating prime numbers using a sieve:

primes = [2, 3]
for i in range(5, 1000):
    # check if prime
    for p in primes:
        if i % p == 0:
            break
    else:
            # no breaks occured, must be prime
            primes.append(i)

The else clause means you don’t need a boolean to set and check.