Bottom Page

Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 illustrate for/else
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
for x in range(3): # this is a loop to repeat the test with x being 0 then 1 then 2
    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('a way to remember:  break or else')
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.

Top Page

Forum Jump:

Users browsing this thread: 1 Guest(s)