Python 6a - For Loops

Types of Loop

The third construct of programming (after Sequence and Selection) is Iteration. If you iterate something then you repeat it.

There are two key loops to use in Python: for loops and while loops.

A for loop is count controlled – e.g. “For 10 seconds I will jump up and down”.
The loop will continue until the count (e.g. 10 seconds) has finished.

A while loop is condition controlled – e.g. “While I am not out of breath I will jump up and down.”
The loop will continue until the condition is no longer true.

Simple For Loops

The i is a count variable, it is used to measure each iteration (turn) of the loop. 

In the range brackets I have written that I want to loop the indented code 10 times.

Don’t forget the colon at the end and remember that everything you want to repeat must be indented (press tab key once).

Practice Task 1

1. Make a simple for loop just like the one above but make it repeat for 5 turns and print your name instead of ‘This is a loop!’.

2. Make another loop and repeat the word hello one thousand times.

Example solution:

Using i to Record Iterations

Let’s make our for loops a bit more complicated.

 

We can refer to the iteration that we are currently on inside the loop itself using i:

Python will always start counting at 0 rather than 1 so our loop is not as we expected.

 

Therefore we need to specify in our range brackets that we want to start at 1 and continue up until (but not including) 11.

Practice Task 2

1. Create a program that loops from 100 to 200 and prints the loop number each time.

 

2. Create another program that starts at 10 and prints the even numbers up to 20...

 

(HINT: Writing a second comma and a third number in the range brackets e.g. range(200,301,10) will state how many the loop number should increase by each turn.

 

range(200,301,10) will increase from 200 up to 300 by 10 each time.)

 

Experiment and see what happens!

 

3. Using your answer to #2 to help you, write a loop that counts backwards from 100 to 0, printing each turn.

Example solution for #2:

Using Variables

We don’t have to put just numbers in a range bracket, we could use a variable.

 

For example, a very simple program where we have asked the user to enter how many times they want to print something:

Lastly, below is a for loop where the user inputs both the range and the text to be repeated:

Practice Task 3

1. Ask the user to input a number.

 

Print “Are we there yet?” that number of times.

 

2. Start another program and ask the user their name and their age.

Print their name the number of times as their age.

Example solution for #1:

© CSNewbs 2019