Python Arena
Step 3 of 4

Default parameter values

A parameter can have a default value, written with = after its name in the def line. When a call leaves that argument out, the parameter gets the default:

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


greet("Ada")
greet("Linus", "Good morning")
greet("Grace", "")
Output
Hello, Ada!
Good morning, Linus!
, Grace!

The last call shows that an empty string is still an argument: the default is used only when the argument is missing. You've relied on defaults all along: print puts a line break at the end unless you give end=..., and range(5) starts from 0 unless you give it a start.

Keyword arguments

With several defaults, a call can name the parameter it gives with a keyword argument, as you've done with sep= and end= in print, and keep the defaults of the others:

def line(length=20, character="-"):
    return character * length


print(line())
print(line(5))
print(line(8, "="))
print(line(character="*"))
Output
--------------------
-----
========
********************

Parameters with a default come after those without one. The other way round, Python couldn't tell which argument belongs to which parameter, and it stops before running anything:

def greet(greeting="Hello", name):
    print(f"{greeting}, {name}!")
Python stops with
  File "main.py", line 1
    def greet(greeting="Hello", name):
                                ^^^^
SyntaxError: parameter without a default follows parameter with a default

A list as a default: a trap

A default value is made once, when the def line runs, not on every call. For a number or a string that doesn't matter. But a list can change, and then every call that uses the default shares the same list:

def add_item(item, basket=[]):
    basket.append(item)
    return basket


print(add_item("apple"))
print(add_item("pear"))
Output
['apple']
['apple', 'pear']

The second call got a basket that already had an apple in it. The usual fix is None as the default, and a new list made inside the function: def add_item(item, basket=None):, with if basket is None: and basket = [] at the start of the body.

Your task

Challenge 1 of 3

Fill in the blank so that times is 2 when the call doesn't give it. The program should print:

haha
hohoho

Challenge 2

Write a function format_price(amount, currency="EUR") that returns the amount with two decimals and the currency after it: format_price(12.5) returns "12.50 EUR", and format_price(3, "USD") returns "3.00 USD".

Challenge 3

Write a function draw_box(width=5, height=3, character="#") that prints a box of the given character, height lines of width characters each. Calls can leave out any of the arguments, or name them. draw_box(4, character="+") prints:

++++
++++
++++