Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 4.3Loops

Part 4.3Loops

Repetition in programming is very common. For instance, methods are defined in Python with the def keyword. The purpose of this is to make code easier to reuse. This saves rewriting the code over and over again.

Almost every programming language out there supports two kinds of loops. They are:

  • Fixed loops
  • Conditional loops

The same goes for removing items from an array - for instance removing each value in the array from 0 to 100 would take a while and means writing pretty much the same code over and over again.

That's where loops come in. A loop is basically a method continuously repeating the same thing either forever (infinite loop) or until some condition is satisfied (conditional loop).

For loop

The for loop is perhaps the most commonly used in Python. Python does however work very differently to a lot of languages (such as ZPE's YASS) in that it requires use of the range function. In fact, Python's for loop is more like a for-each loop.

The following loop will generate numbers from 1 to 9 and print them:

Python
for x in range(1, 10):
  print (x)
    

That's all there is to the standard for loop. For the for-each loop it works almost identically, and it works on iteratable values such as lists (note, the range function also generates a list, hence why this works with this method.)

Python
for x in [0, 1, 2, 3]:
  print (x)
    

With both loops it is important to note the use of the colon (:).

While loop

The while loop differs from the for loop and is rarely seen in Python. The while loop is started with the while keyword:

Python
x = 0
while x < 10:
  print (x)
  x += 1
    

While loops can also be used to create infinite loops, that is a loop that never ends (but they can broken out of):

Python
x = 0
while True:
  print (x)
  x += 1
    

Breaks

Most programming languages support the use of infinite loops which can be escaped from. In most programming languages it's called a break.

An infinite loop, like the previous example, is not often very useful. It is often the case that the break keyword is found within the loop somewhere to stop the execution of the loop:

Python
x = 0
while True:
  print (x)
  x += 1
  if x > 100:
    break
    

In this example when x becomes equal to 101 the loop stops.

Feedback 👍
Comments are sent via email to me.