Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.

Default Arguments

~8 mincode completion

A parameter can have a default, which makes it optional at the call site:

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

greet("Ada")                      # "Hello, Ada"
greet("Ada", "Good evening")      # "Good evening, Ada"
greet("Ada", greeting="Hi")       # "Hi, Ada"     <- named, clearer

Two rules:

  • Parameters with defaults must come after the ones without. def f(a=1, b) is a syntax error.
  • Passing an argument by name (greeting="Hi") is almost always more readable than by position once there are more than two, which is why library functions you will meet later are full of them.
  • Your task:

    Write apply_discount(price, percent=10) that returns the price after taking off a percentage. The default is 10 percent.

    apply_discount(200) returns 180.0. apply_discount(200, 25) returns 150.0.

    Example Tests

    With no percentage given, the 10 percent default applies

    Input: {"price":200}

    Expected: 180

    An explicit percentage overrides the default

    Input: {"price":200,"percent":25}

    Expected: 150

    A 0 percent discount leaves the price alone

    Input: {"price":99,"percent":0}

    Expected: 99

    Python
    def apply_discount(price, percent=10):
        """
        Reduce a price by a percentage.
    
        Args:
            price: the original price
            percent: the discount percentage, defaulting to 10
    
        Returns:
            The price after the discount.
        """
        # YOUR CODE HERE
        pass

    Run your code to see results

    ⌘↵ runs against the visible tests

    Loading docs…