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.
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).
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 method. 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:
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
method also generates a list, hence why this works with this method.)
for x in [0, 1, 2, 3]: print (x)
With both loops it is important to note the use of the colon (
The while loop differs from the for loop and is rarely seen in Python. The while loop
is started with the
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):
x = 0 while True: print (x) x += 1
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:
x = 0 while True: print (x) x += 1 if x > 100: break
In this example when x becomes equal to 101 the loop stops.