Exercise 5: 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))

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

Exercise 4: Conditions
Exercise 6: While loop