Loops

Loops are another great way to keep you from repeating yourself, especially when you need to perform the same action to a group (for example, a list) of items. Let’s take a look:

For Loop

Something is an iterable if you can iterate over it using a “for loop”. Strings and lists are both iterables.

Let’s make a for loop:

>>> fruits = ["strawberries", "bananas", "apples", "oranges"]
>>>
>>> for fruit in fruits:
...     print(fruit)
...
strawberries
bananas
apples
oranges

Here, fruit is a variable name which will contain a different item in each iteration of the loop.

We can use any name we like for this variable:

>>> for x in fruits:
...     print(x)
...
strawberries
bananas
apples
oranges

Your Turn: Loops 🏁

Loop Exercises

Say Hi to a List

Create a list of names and print a personal hello to each person on the list.

Looping Number Guesser

Refactor your number_guesser.py program to use loops to allow only 3 tries.

Chore Chooser

Make a program chore_chooser.py that does the following:

  1. Create two lists do_now and do_later, along with a list of chores
  2. Assign each item in the list of chores to do_now or do_later at random
  3. Print each list in a nice, human-readable way

Highest Population Capital City

Using the provided file list-state-capitals-us.csv, find and print the name of the state with the capital city that has the highest population.