Thursday 1 May 2014

Loops in Python

For loops

Usage in Python

  • When do I use for loops?
For loops are traditionally used when you have a piece of code which you want to repeat n number of times. As an alternative, there is the WhileLoop, however, while is used when a condition is to be met, or if you want a piece of code to repeat forever, for example -
For loop from 0 to 2, therefore running 3 times.
for x in range(0, 3):
    print "We're on time %d" % (x)
While loop from 1 to infinity, therefore running infinity times.
x = 1
while True:
    print "To infinity and beyond! We're getting close, on %d now!" % (x)
    x += 1
As you can see, they serve different purposes. The for loop runs for a fixed amount - in this case, 3, while thewhile loop theoretically runs forever. You could use a for loop with a huge number in order to gain the same effect as a while loop, but what's the point of doing that when you have a construct that already exists? As the old saying goes, "why try to reinvent the wheel?".
  • How do they work?
If you've done any programming before, there's no doubt you've come across a for loop or an equivalent to it. In Python, they work a little differently. Basically, any object with an iterable method can be used in a for loop in Python. Even strings, despite not having an iterable method - but we'll not get on to that here. Having an iterable method basically means that the data can be presented in list form, where there's multiple values in an orderly fashion. You can define your own iterables by creating an object with next() and iter() methods. This means that you'll rarely be dealing with raw numbers when it comes to for loops in Python - great for just about anyone!
  • Nested loops
When you have a piece of code you want to run x number of times, then code within that code which you want to run y number of times, you use what is known as a "nested loop". In Python, these are heavily used whenever someone has a list of lists - an iterable object within an iterable object.
  • Early exits

Like the while loop, the for loop can be made to exit before the given object is finished. This is done using thebreak keyword, which will stop the code from executing any further. You can also have an optional else clause, which will run should the for loop exit cleanly - I.E., without breaking.

No comments:

Post a Comment

Wildern Pupils if you log onto your school email account you can leave a comment via that ID.