Python Loops

A loop statement allows the execution of a statement or group of statements multiple times. There are two types of loop statement in Python.

  • ‘for’ loop – Useful when it is known in advance the number of times the statements within the loop need to be executed.
  • ‘while’ loop – Repeats a statement or group of statements while an expression evaluates to true. There is a condition to get into the loop, so if the condition evaluates to true at the beginning then the statements inside the loop will never execute.

As with ‘if’ statements, the indentation of statements within a loop is very important because an indentation error will otherwise be generated.

‘for’ Loop

A ‘for’ loop in Python comes in two forms, the first of which a range of numbers is specified that dictates the number of times the loop is executed, whilst the second loops through the items in a sequence, such as the characters in a string.

A ‘for’ loop that includes a range takes the following form.

for range_variable in range(range_start,range_end):
   # Statement(s) to execute.

The ‘range_start’ and ‘range_end’ specify the start and end of the range, another words the number of times that the statements in the loop are executed. Note that if the range values are 1 and 5, the loop executes four times and not five, it starts at the ‘range_start’ value and goes up to, but not including the ‘range_end’ value. The ‘range_variable’ is the current value of the range, so if the ‘range_start’ is 1, then the ‘range_variable’ will be 1 the first time through the loop.

Below is an example of a ‘for’ loop with a range from 1 to 5, that outputs the ‘range_variable’ to the console each time through the loop.

for num in range(1,5):
   print(num)

The output from this loop is shown below.

1
2
3
4

A ‘for’ loop that iterates through a sequence takes the following form.

for sequence_variable in sequence:
   # Statement(s) to execute.

A ‘sequence’ is anything that Python can iterate through, for example a string of characters. In the case of a string, the ‘sequence_variable’ contains the current character. The example below iterates through the string ‘Python’ and outputs each character, one at a time to the console.

for letter in 'Python':
   print (letter)

The resulting output can be seen below.

P
y
t
h
o
n

‘while’ Loop

As mentioned above, the ‘while’ loop has a condition, which must evaluate to true before the statements within it can be executed.

while condition:
   # Statement(s) to execute.

In the below example, a variable is declared and initialised to zero, then the ‘while’ loop checks to see that the variable is less than five before outputting it to the console and incrementing the variable by one.

i = 0
while i < 5:

   print(i);
   i += 1

The resulting output is as follows.

0
1
2
3
4