Skip to content

Nested loops

Related course:

Nested loops

A loop can contain one or more other loops. This principle is known as nested loops.

Lets do a simple example. If we have a list of persons who like to eat at restaurants, can we make
every one of them eat a certain restaurant?


persons = [ "John", "Marissa", "Pete", "Dayton" ]
restaurants = [ "Japanese", "American", "Mexican", "French" ]

for person in persons:
    for restaurant in restaurants:
        print(person + " eats " + restaurant)

What you see on success

You should see this output:


Try the exercises below

1. Given a tic-tac-toe board of 3x3, print every position

2. Create a program where every person meets the other
   persons = [ "John", "Marissa", "Pete", "Dayton" ]

3. If a normal for loop finishes in n steps O(n), how many steps has a nested loop?

After completing these continue with the next exercise.


Write file
Published inUncategorized

Be First to Comment

    Leave a Reply