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
>Solution :
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