Default Values

Default Values

A parameter can have a default value, written with = in the definition. If the caller leaves that argument out, the default is used:

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}."

print(greet("Parsnip"))
print(greet("Parsnip", "Good morning"))

Output:

Hello, Parsnip.
Good morning, Parsnip.

The first call omitted greeting, so it got "Hello". The second call supplied it.

Parameters with defaults must come after parameters without them. def greet(greeting="Hello", name) is an error.

Exercise

  1. Define a function named format_price with two parameters: amount, and currency with the default value "AUD".
  2. It returns an f-string in the form <amount> <currency>.

For example, format_price(120) returns "120 AUD", and format_price(120, "USD") returns "120 USD".

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

Tests

import unittest


class TestFormatPrice(unittest.TestCase):
    def test_default_currency_is_aud(self):
        self.assertEqual(format_price(120), "120 AUD")

    def test_explicit_currency_overrides_the_default(self):
        self.assertEqual(format_price(120, "USD"), "120 USD")

    def test_other_amounts_work(self):
        self.assertEqual(format_price(5), "5 AUD")
def format_price(amount, currency="AUD"):
    return f"{amount} {currency}"


print(format_price(120))
print(format_price(120, "USD"))
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.