Control Flow Loops
While Loop
A while loop will repeat a block of statements while a condition is true. This code will print out the contents of the items in the list. This code uses a function called len , which is a built-in function that returns the length of a list or string.
listOfFruit = [
'Apples'
,
'Oranges'
,
'Bananas'
]
x =
0
while
x < len(listOfFruit):
print listOfFruit[x]
x = x +
1
For Loop
Python's for loop may be a bit different than what you're used to if you've programmed any C. The for loop is specialized to iterate over the elements of any sequence, like a list. So, we could re-write the example above using a for loop eliminating the counter x:
listOfFruit = [
'Apples'
,
'Oranges'
,
'Bananas'
]
for
item in listOfFruit:
print item
Much more graceful! You'll often see the for loop used instead of the while loop, even when you simply want to iterate a given number of times. To do this with the for loop, you can use the built-in function range. The range function returns a variable-size list of integers starting at zero. Calling range(4) will return the list [0, 1, 2, 3]. So, to have a for loop repeat 4 times, you simply can do:
for
x in range(
4
):
print
"this will print 4 times"
Break and Continue In Loops
You can stop a loop from repeating in its tracks by using the break statement. This code will print out " Loop " exactly two times, and then print " Finished ".
for
x in range(
10
):
if
x >=
2
:
break
print
"Loop"
print
"Finished"
You can use the continue statement to make a loop stop executing its current iteration and skip to the next one. The following code will print out the numbers 0-9, skipping 4
for
x in range(
10
):
if
x ==
4
:
continue
print x