Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python — loop-else basic principle

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading