Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Build your toolkit
EXPERIMENT 16 / 101

Inputs with good defaults.

Use defaults and keyword arguments to make functions pleasant to call.

BY NAVAN SAMI◷ 6 MIN READPYTHON 3

01 The idea

Parameters describe the inputs a function accepts. Default values make some inputs optional. Keyword arguments identify an input by name, making calls clearer when several values have similar types. Required parameters must be provided unless a default exists.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

arguments.py
def mission_label(name, priority="normal"):
    return f"{name}: {priority}"

print(mission_label("Orbit"))
print(mission_label("Orbit", priority="high"))
↳ EXPECTED OUTPUT
Orbit: normal
Orbit: high

03 Under the hood

  1. 1

    The first call omits priority, so the default "normal" is used. The second call overrides it by name.

  2. 2

    Defaults are evaluated when Python executes the function definition, not afresh for every call. That matters when a default is mutable.

  3. 3

    To collect optional items safely, use a None default and create a new list inside the function. *args can collect extra positional arguments; **kwargs can collect extra named arguments when an interface needs that flexibility.

04 Your turn, builder

A SMALL MISSION

Write greet(name, greeting="Hello") and call it once with the default and once with greeting="Hey".

Reveal one possible solution +
one_possible_solution.py
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Navan"))
print(greet("Navan", greeting="Hey"))

05 Check your signal

QUICK SIGNAL CHECK

When is a default parameter value evaluated?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.