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

Loop Exercises

Meditative Breathing Guide

Tip

You may have already done this exercise without using a for loop. Try to adapt your code to use a loop instead!

Copy rand.py and make a program breathe.py which helps users breathe one breathe every 12 seconds by printing out "Breath in", waiting 6 seconds, then saying "Breath out", waiting 6 seconds, and then repeating. It should do this for 2 minutes.

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