Repetition

PYTHON FLEXIBILITY

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

For Example

In this example you will see that Python doesn’t follow the norm for for loops.

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.

but this can be simplified, if we only want to print out the words, to:

You can also do this for each letter in a word.

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.

About CDB 362 Articles
Self-Employed Software Developer, Spark, Property Management, Hobby Forestry, Ex-Teacher, Engineering - Wood, Metal, Electrics & Computers. Outdoors - Walk, Cycle, Kitesurf,

Be the first to comment

Leave a Reply

Your email address will not be published.


*


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