Programs sometimes need to repeat actions. To repeat actions we can use a for loop.
A for loop is written inside the code. A for loop can have 1 or more instructions.

A for loop will repeat a code block. Repeation is continued until the stop condition is met. If the stop condition is not met it will loop infintely.

These instructions (loop) is repeated until a condition is met.

Related course: Complete Python Programming Course & Exercises

Example

In the exercise below we will repeat actions on every item of a list.

The first loop will repeat the print functionfor every item of the list.
The second loop will do a calculation on every element of the list num and print the result.

Type the code below and run the program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python3

city = ['Tokyo','New York','Toronto','Hong Kong']
print('Cities loop:')
for x in city:
print('City: ' + x)

print('\n') # newline

num = [1,2,3,4,5,6,7,8,9]
print('x^2 loop:')
for x in num:
y = x * x
print(str(x) + '*' + str(x) + '=' + str(y))

Save the file as loopexample.py
Then run the code with the command:

1
python loopexample.py

Schematically a for loop does this:

for loop

If you are a beginner, then I highly recommend this book.

Exercise

Try the exercise below:

1. Make a program that lists the countries in the set

1
clist = ['Canada','USA','Mexico','Australia']

2. Create a loop that counts from 0 to 100
3. Make a multiplication table using a loop
4. Output the numbers 1 to 10 backwards using a loop
5. Create a loop that counts all even numbers to 10
6. Create a loop that sums the numbers from 100 to 200

Download examples