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

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:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.