Python knows break and continue. The else clause is executed, if for is normally exhausted. Here are loop examples:
#!/usr/local/bin/python
a = [ 'cats', 'and', 'dogs']
for x in a:
print( x,)
print()
#
# range( 10) runs from 0 to 9
#
for i in range( len( a)):
print( i, a[i])
In the following example it is tested whether the loop exhausted.
#!/usr/local/bin/python
#
# range( 2, 100) runs from 2 to 99
#
for n in range(2, 100):
for x in range(2, n):
if n % x == 0:
print( n, 'equals', x, '*', n/x)
break
else:
# loop fell through without finding a factor
print( n, 'is a prime number')
The following loops run over list elements:
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.iteritems():
print( k, v)
#
# -> gallahad the pure
# -> robin the brave
#
for i, v in enumerate(['tic', 'tac', 'toe']):
print( i, v)
#
# -> 0 tic
# -> 1 tac
# -> 2 toe
# zip allows to loop over two sequences at the same time
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print( 'What is your %s? It is %s.' % (q, a))
#
# -> What is your name? It is lancelot.
# -> What is your quest? It is the holy grail.
# -> What is your favorite color? It is blue.
#
for element in [1, 2, 3]:
print( element)
for element in (1, 2, 3):
print( element)
for key in {'one':1, 'two':2}:
print( key)
for char in "123":
print( char)
for line in open("myfile.txt"):
print( line)
Some while loops:
#
# while
#
while 1:
print( "running forever ")
while a > b:
print( "a > b")
if a == 10:
break
else:
print( "we didn't hit a <break>")