Fixed Loops

Fixed loops allow code to be repeated a set number of times. All instructions inside this loop will run for each repeat of the loop.

Key Points

Fixed Loops run a set number of times, no more, no less.

The number of times a loop will repeat is set in its range().

The index of a fixed loop can be used inside the loop.

Creating a Fixed Loop

The following code is used to create a fixed loop that repeats 5 times.

As a result of repeating 5 times, the output will say ‘Hello’ 5 times.

for i in range(5):
    print("Hello")

Setting the Range

The range sets how many times the code repeats and is set by putting the number, or a variable, inside the brackets as a parameter.

In the below example, the range is set as a variable and used when creating the fixed loop.

loops = 10

for i in range(loops):
    print("Hello")

The range can also be set by asking a user for a number.

In the following example, a user is asked for a number and the variable is then used as the range.

loops = int(input("How many times do you want to loop? "))

for i in range(loops):
    print("Hello")

Using the Index

The index (i) of a fixed loop starts at 0 and increases by 1 each time the fixed loop runs.

Because the index starts at 0, if the range of a loop is 10, the highest value of the index will be 9.

The index can be used inside of the loop.

In the below example, i is printed out each time the loop runs, printing out the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9.

for i in range(10):
    print(i)

The index can be used like any other variable however it is limited to being used inside of the loop.

In the below example, the index is multiplied by 5 to print out the 5 times table.

for i in range(10):
    print(i*5)

National 5 Requirements

You should be able to identify a fixed loop and explain how it works.

You should be able to implement a fixed loop into your code.