Skip to content

For Loops

Related course:

For loops

Programs sometimes need to repeat actions. To repeat actions we can use a for loop. 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))

You should see:


Do these exercises:

1. Create a loop that prints every city in the list ['Barcelona','Madrid','Bilbao','Paris']
2. Create a loop that counts from 1 to 10

Once completed continue with the next exercise.


If statements
While loop
Published inUncategorized

Be First to Comment

    Leave a Reply