Python - Loops

Iteration is when you create a program that repeats or loops through a piece of code a number of times.

Here we can see an example of iteration in a Scratch program.

What do you think will happen when we press the green flag?

Press the Green Flag to see the output of this program

We can create a similar program in Python like the code below...

We use the keyword while to say keep doing something while the condition (the comparative statement) is true. In this case keep looping while i is less than or equal to 10.

Create a new program file and type in the code and give it a go!

There is one thing that you really need to be careful of… the infinite loop of doom!

Create a new program file and type in and run the following piece of code!

What do you think will happen?

You may need to click “Shell” -> “Restart”

When programing a while loop in Python you always need to have a variable ready to be tested. In the examples above the variable was i.

The variable must be changed inside the loop, otherwise the loop will never end (the infinite loop).

In the second example above, i is always less than 10 because we never change it. Therefore the loop never ends, and the program will never finish.

Watch the video below to see how to create a while loop in Python

pythonLoops.mp4

Challenges

What Number Shall we count to?

Create a program that will ask the user what number to count up to (starting form 1).


The Two Times Table

Create a program that can display the first 12 numbers of the two times table.

Times Table Machine

Create a program that will ask the user what times table to output.

The program should loop 12 times outputting the first 12 numbers of that times table.

Key Words

Loop

A data structure that allows the code inside it to be repeated.

Iteration

The process of repeating.

Infinite Loop

A loop that never stops iterating.

Condition

A test (normally a comparative statement) that returns true or false.

Variable

A place where data is stored whilst the program is running. The data value can change during the program.