-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)
OscarVFE
  • 5
  • 1

1 Answers1

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.

L3viathan
  • 26,748
  • 2
  • 58
  • 81