Friday, August 7, 2009

tic-tac-toe: loop detail

In the program I'm writing, I have code structured like this:

for i in range(2):
print 'i', i
for p in 'xy':
print 'p', p
if True:
continue


What I want is to continue back to the next i (outer loop), rather than the next p (inner loop). This code doesn't do that:

i 0
p x
p y
i 1
p x
p y


It's not elegant, but what I did was add a flag labeled C. We check the value of C before starting the inner loop.

for i in range(2):
print 'i', i
C = False
for p in 'xy':
if C: continue
print 'p', p
if True:
C = True


That does what I want:

i 0
p x
i 1
p x