illustrate for/else - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Code sharing (https://python-forum.io/forum-5.html) +--- Thread: illustrate for/else (/thread-29682.html) |
illustrate for/else - Skaperen - Sep-15-2020 this code is for educational purpose to show the effect of for followed by else. # this is just to illustrate how for followed by else works import os print() for x in range(3): # this is a loop to repeat the test with x being 0 then 1 then 2 print('-'*64) print('in outer loop x =',x) for n in range(2): # this is the test loop followed by an else print('-------- in inner loop n =',n) if n == x: # do the break at 0 then 1 then 2 which n will never be print('break out ---- n =',n,', x =',x) break # this is a break to escape the test loop to see where it goes print('---- end of inner loop n =',n) # this is where inner loop ends else: # the else must directly follow the end of the loop (comments don't matter) print('this is the else clause ---- n =',n,', x =',x,'so there was no break') print('after the inner loop ---- n =',n,', x =',x) print('-'*64) print('a way to remember: break or else') print('-'*64) |