Parameters

Parameters

A parameter is a variable listed inside the parentheses of a function definition. It lets the caller pass a value in.

def greet(name):
    print(f"Hello, {name}.")

name is a parameter. Inside the body it works like any variable. The value for it is supplied at the call, that value is called the argument:

def greet(name):
    print(f"Hello, {name}.")

greet("Parsnip")
greet("Python")

Output:

Hello, Parsnip.
Hello, Python.

Each call runs the same body with a different value for name. This is what makes a function reusable: one definition, many inputs.

Calling a function that has a parameter without an argument is an error:

greet()

Output:

TypeError: greet() missing 1 required positional argument: 'name'

Exercise

  1. Define a function named announce with one parameter, city. It prints exactly:

Now arriving in <city>.

For example, announce("Sydney") prints Now arriving in Sydney. 2. Below the definition, call announce with a city of your choice.

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 TestAnnounce(unittest.TestCase):
    def test_announce_sydney(self):
        self.assertEqual(output_of(announce, "Sydney"), "Now arriving in Sydney.\n")

    def test_announce_perth(self):
        self.assertEqual(output_of(announce, "Perth"), "Now arriving in Perth.\n")
def announce(city):
    print(f"Now arriving in {city}.")


announce("Sydney")
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.