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.

for loop

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

Related course: Complete Python Bootcamp: Go from zero to hero in Python


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.

#!/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))


Try the exercise below:

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

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

Download answers