-1

My question is why there is such a thing as an "else" clause in a while loop. My code, for example, looks like this:

a = 100
turns = 0
while a > 0:
    if func(a, b): #Function returns boolean value
        a -= 1
        turns += 1
    else:
        a -= 2
        turns += 1
else:
    print(turns)

The question being, how is this any different from following syntax?

a = 100
turns = 0
while a > 0:
    if func(a, b): #Function returns boolean value
        a -= 1
        turns += 1
    else:
        a -= 2
        turns += 1
print(turns)
0

1 Answer 1

0

The difference is how it handles abnormal exiting of the loop, e.g. a break:

while True:
    break
else:
    print("not printed")
print("printed")

The same applies to exceptions raised inside the loop body.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.