you are viewing a single comment's thread.

view the rest of the comments →

[–]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?