Skip main navigation

Looping a Set Number of Times

Learn more about looping a set number of times.
Looping A Set Number Of Times

Being able to run the same piece of code a number of times can be really useful. Say you want to capture eleven names for a football team, or the lengths of the sides of a triangle. You can do this by adjusting the way you use a for loop.

 

To do something five times, you could create a for loop that looped for all the numbers between 0 and 4 by creating a list of those numbers, for example:

 

numbers = [0,1,2,3,4]
for number in numbers:
 print(number)

 

However, this is very restrictive. It will only ever be able to loop five times, and what happens if you want to do something a million times? It wouldn’t be feasible to create a list with every number up to 1,000,000.

 

To overcome this issue, Python has a function called range that will create a list of numbers for you.

 

By using range we can simplify the example program above:

 

for number in range(5):
 print(number)

 

Note: The function range(5) will create a list of five numbers from 0 to 4, not six numbers from 0 to 5.

 

You will now use a for loop with range to create a program that will loop for a set number of times, asking the user for an item of shopping and then appending it to the shopping list variable.

 

 

    • Create a new program and save it as create_shopping

       

 

    • Create an empty list variable called shopping

       

 

 

shopping = []

 

 

    • Add a for loop with a range to loop five times

 

 

for item_number in range(5):

 

 

    • Indented under the for loop, use input to ask the user for something to add to the shopping list

 

 

 item = input("what is the item? ")

 

 

    • Still indented under the for loop, append the item to the shopping list

 

 

 shopping.append(item)

 

 

    • Finally, after the for loop, let’s print the shopping list, so we can see what is on it

 

 

print(shopping)

 

The complete create_shopping program should now look similar to this:

 

shopping = []

for item_number in range(5):
 item = input("what is the item ? ")
 shopping.append(item)

print(shopping)

 

 

    • Run your program and make sure that you can enter five items of shopping, and that they are displayed at the end

 

 

Mu, with the code above in the editor. In the REPL the question 'what is the item ? ' is asked 5 times, with the responses 'raspberry pi', 'power supply', 'sd card', 'keyboard' and 'mouse'. The final line reads "['raspberry pi', 'power supply', 'sd card', 'keyboard' and 'mouse']"

 

At each stage, the variable item_number will contain the number of the times the program has been around the for loop, starting at 0 and going up to 4. Let’s make this more apparent.

 

 

    • Change your program to include each item_number in the corresponding prompts to the user for shopping items

 

 

 item = input("what is item number " + str(item_number) + "? ")

 

 

    • Run your program so you can see this displaying each item_number

 

 

Mu, with the code above except line 4 has been changed to 'item = input("what is item " + str(item_number) + "? ")', indented under the 'for'. The REPL shows input statements of the form 'what is item number 0?', each on a separate line with the item number starting at 0 and increasing by 1 each time up to 4. The responses to these are 'coffee', 'milk', 'sugar', 'sprinkles' and 'cup'. The final line reads "[ 'coffee', 'milk', 'sugar', 'sprinkles','cup']"

 

Reflect: Make sure that you can explain in your own words what each line of code does here. You may want to work through what’s going on in the program on paper, making sure to increase item_number for each iteration of the for loop.

 

At the moment, your program will only ever collect five items of shopping. What if you have more items, or fewer? In the next step you will change the program so that it starts by asking the user how many items of shopping they need, and uses that number in the for loop.

 

 

    • Add to the top of your program an input to get the number of items of shopping

 

 

how_many = input("how many items of shopping do you have? ")

 

 

    • The variable how_many will be a string, so use int to cast it to an integer

 

 

how_many = int(how_many)

 

Note: Rather than creating a new variable to hold the how_many integer, called, for example, how_many_number, you have cast the how_many variable back to itself. You no longer need the string variable how_many so you may as well overwrite it with an integer variable!

 

 

    • Now change the for loop so that the variable how_many is used by range

 

 

for item_number in range(how_many):

 

Your program should now look similar to this:

 

shopping = []

how_many = input("how many items of shopping do you have? ")
how_many = int(how_many)

for item_number in range(how_many):
 item = input("what is item number " + str(item_number) + "? ")
 shopping.append(item)

print(shopping)

 

 

    • Run your program and enter a number of items

 

 

Mu, with the new code above in the editor. In the REPL, the first line reads 'how many items of shopping do you have?' followed by the response '3'. The next three lines contain input statements of the form 'what is item number 0?', each on a separate line with the item number starting at 0 and increasing by 1 each time up to 2. The responses to these are 'tea', 'lemon' and 'cup'. The final line reads "['tea', 'lemon', 'cup']"

 

You have now learnt how to use a for loop. We will look at other forms of looping next week.

This article is from the free online

Programming 101: An Introduction to Python for Educators

Created by
FutureLearn - Learning For Life

Our purpose is to transform access to education.

We offer a diverse selection of courses from leading universities and cultural institutions from around the world. These are delivered one step at a time, and are accessible on mobile, tablet and desktop, so you can fit learning around your life.

We believe learning should be an enjoyable, social experience, so our courses offer the opportunity to discuss what you’re learning with others as you go, helping you make fresh discoveries and form new ideas.
You can unlock new opportunities with unlimited access to hundreds of online short courses for a year by subscribing to our Unlimited package. Build your knowledge with top universities and organisations.

Learn more about how FutureLearn is transforming access to education