The following code is from my homework. I have the question and I also have the answer, but I don't understand how to get the answer.
#Question
result = 0
for n in range(3):
print(n, end=' ')
result -= 3
else:
print('| {}'.format(result))
print('done')
#Answer
0 1 2 | -9
done
The for loop is using a range of 0-2, so I expect it to run through the loop all 3 times and produce the '0 1 2' part, but why does it add the 'else' portion? Shouldn't it only use the 'else' portion if the loop statement evaluates as 'False' but how is it false if the loop knows to only run 3 times and none of the first 3 statements evaluate as false? Or does the else always evaluate when it's a loop-else? I assume I'm missing some fundamental knowledge here. TIA
CodePudding user response:
We use else with for loops to check that if the for loop has reached the end without a break for exmaple:
for i in range(5):
print(i)
if (i == 3):
break
else:
print("iterated over the whole range")
this will only print numbers from 0 to 3 and then stop without printing the message because we have broke out of the loop.
note that not many programming languages support putting else after a loop.
CodePudding user response:
A for
loop's else
clause is executed when all iterations finish executing without interruption (i.e.: without encountering a break
).
If a break
is encountered within the for
loop, the else
won't be executed.
See the Python documentation: https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops