For loops are used to iterate an iterable. They are most often used to execute code n about of times.
for i in xrange(1, 3): print i
1 2 3
for i in xrange(1, 3): for j in xrange(i, 4): print i, j
Code block after else is executed after after the for, but only if loop is terminates in standard way (brake statement is not used)
for i in xrange(1, 3): print i else: print 'after for'
1 2 3 after for
While loop, like for, is used for executing code many times. Main difference between those two is fact that while loop isn't executed n times, but until a defined condition is false.
Loop control statementsEdit
Loop control statements change standard loop execution flow.
while result = do_something(): print result
Execution of this loop is stopped do_something() returns False
Break terminates the current loop and resume next statement execution.
for i in (1, 2, 3): if i == 2: break print i print 'test'
Continue stops execution of current iteration and moves the control back to the top of next iteration.
for i in (1, 2, 3): if i == 2: continue print i print 'test'
1 3 test
Pass statement is a *null* operator in Python. Nothing happen when it executes. It's placeholder used when statement is required by syntax, but no code is needed to be executed.
for i in (1, 2, 3): pass