For Loops

For Loops

A for loop runs a block once for each element of a list:

names = ["Ada", "Grace", "Alan"]
for name in names:
    print(f"Hello, {name}.")

Output:

Hello, Ada.
Hello, Grace.
Hello, Alan.

name is the loop variable. On the first pass it holds "Ada", on the second "Grace", on the third "Alan". The indented block is the loop body; like a function body or an if block, indentation marks where it starts and ends.

The loop variable is a new name — pick one that describes a single element. Looping over prices, call it price.

The body can contain anything, including an if:

for name in names:
    if name == "Grace":
        print("Found Grace.")

Output:

Found Grace.

Exercise

  1. Define a function named announce_all with one parameter, cities (a list).
  2. For each city, print exactly Now arriving in <city>. — one line per city, in list order.

Run your code to see the output, then press Submit.

Tests

import io
import unittest
from contextlib import redirect_stdout


def output_of(function, *args):
    captured = io.StringIO()
    with redirect_stdout(captured):
        function(*args)
    return captured.getvalue()


class TestAnnounceAll(unittest.TestCase):
    def test_three_cities_give_three_lines_in_order(self):
        expected = "Now arriving in Sydney.\nNow arriving in Melbourne.\nNow arriving in Perth.\n"
        self.assertEqual(output_of(announce_all, ["Sydney", "Melbourne", "Perth"]), expected)

    def test_one_city(self):
        self.assertEqual(output_of(announce_all, ["Paris"]), "Now arriving in Paris.\n")

    def test_empty_list_prints_nothing(self):
        self.assertEqual(output_of(announce_all, []), "")
def announce_all(cities):
    for city in cities:
        print(f"Now arriving in {city}.")


announce_all(["Sydney", "Melbourne", "Perth"])
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.