Python only has two ways of doing loops (KISS), while
and for
5.1 define a while loop
def main(): x = 0 # define a while loop while (x < 5): print x x = x + 1 if __name__ == "__main__": main()
Performs as expected.
5.2 define a for loop
def main(): x = 0 # define a for loop for x in range(5,10): print x if __name__ == "__main__": main()
Performs as expected.
In Javscript you set up a for loop
with the iterator (usually people use i
) as in for (i=0; i<10; i++)
in python this is replaced by the range iterator for x in range(a,b):
5.3 use a for loop over a collection
def main(): x = 0 # use a for loop over a collection days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"] for d in days: print d if __name__ == "__main__": main()
Straight forward.
Since days
is a range of things we don't need to use the range()
method in the for loop
, just use for
, very simple syntax.
There's no index counter involved. (I wonder what you do if want an index counter? - See enumerate below...)
5.4 use the break and continue statements
def main(): x = 0 # use the break and continue statements for x in range(5,10): #if (x == 7): break #if (x % 2 == 0): continue print x if __name__ == "__main__": main()
Uncomment the break line. It stops the loop when the condition is met. No surprises there.
Uncomment the continue line. It continues on through the loop, skipping the iteration when the condition is met.
x % 2 == 0
- the percent sign is the modulo operator, which means the value of the left over after a division operation. Take whats left over after x is divided by 2, is it equal to 0? Thats a test for the first even number it encounters. In this case the number 6.
5.5 using the enumerate() function to get index
def main(): x = 0 #using the enumerate() function to get index days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"] for i, d in enumerate(days): print i, d if __name__ == "__main__": main()
There you go, there's your index for you to play with...