Repetition
In Python there are many ways to loop some code. Python is quite flexible in its ability to loop however it doesn’t always follow the normal rules. All the following examples print out the numbers 0 to 9
While Example
count=0 while count < 10 : print (count) count = count + 1
For Example
In this example you will see that Python doesn’t follow the norm for for loops.
for a in range (10) : print (a)
However the second example does show the flexibility in this approach. Here we can easily iterate over an array of words, processing each one in turn.
a = ['Mary', 'had', 'a', 'little', 'lamb'] for i in range ( len (a) ) : print (i, a[i])
but this can be simplified, if we only want to print out the words, to:
a = ['Mary', 'had', 'a', 'little', 'lamb'] for i in a: print ( a )
You can also do this for each letter in a word.
word = "pythoniscool" for letter in message: print(letter)
Python also allows for loops to have an else clause (something not seen in other languages). The else clause is called when the for loop reaches it’s count limit.