Loops
Much of the power in programming comes from being able to repeat calculations, and change how our program works depending on the values of certain variables along the way. To achieve this, we need to employ ‘loop expressions’ and build on our use of ‘conditional expressions’.
Loops allow you to repeat a series of calculations a number of times, or until certain conditions are met. In Python, there are two main loop formats.
The while
loop
The first is a while
loop:
while <condition>:
[...]
Here, <condition>
is a logical expression (just like those discussed above). If this evaluates to True
, the block of code ([...]
) is executed in its entirety. The condition is then evaluated again, and the entire process repeats until it becomes False
. For example, here is a loop that keeps doubling a number until it exceeds some threshold:
= 1
x while x<100:
+= x
x print(x)
Normally, the entire indented block of code below the while
statement is executed before the condition is checked again. However, two commands can be used to alter this:
The
break
keyword terminates the loop, jumping to the first statement after the indented blockThe
continue
keyword skips over any remaining code within the indented block, but returns to re-evaluate the<condition>
, and if this is True will execute the indented block as before.
These two commands are almost invariably used in conjunction with an if
statement.
For example:
= 1
x while x < 100:
+=5
xif x == 71:
break
if x%2 == 0:
continue # Skip even values of x
print("In loop: x=", x)
print("After loop: x=", x)
If you run this code, you will see that it never prints an even number (since the print statement is after the continue
in this case, and so doesn’t get executed); moreover, the loop terminates at x=71
, due to the break
statement.
Breaking to exit a loop
Sometimes, it may be appropriate to use the following style:
while True:
[...]if <condition>: break
[...]
Here, the loop condition is always True
, creating an infinite loop. However, the use of a break
allows us to escape from the loop.
Note: there are other loops that we can use in python (e.g. the for
loop) and we will see these later.