liveBook · Manning

Default value

As explained in Python Workout: 50 ten-minute exercises

A function parameter that has a predefined value when the caller omits it.

A default parameter gives a function a predefined value when the caller omits that argument. It lets one function handle both explicit and omitted inputs without requiring multiple definitions. section 6.0

Optional greeting

def hello(name='world'): return f'Hello, {name}!' hello() # 'Hello, world!' hello('out there') # 'Hello, out there!' hello('a', 'b') # TypeError: too many arguments The first parameter remains usable as a normal argument, but omission selects its default. A missing required parameter instead raises an error. section 6.0

Use a default when the number of parameters is known but one value is optional. Prefer it to *args when the function expects a specific optional value rather than an arbitrary number of values. section 6.2

Building flexible XML output

def myxml(tagname, content='', **kwargs): attrs = ''.join([f' {key}="{value}"' for key, value in kwargs.items()]) return f'<{tagname}{attrs}>{content}</{tagname}>' myxml('p') uses an empty string for omitted content, while callers can still provide content and keyword attributes. A similar pattern supports a summing function whose optional starting value defaults to 0. section 6.2 section 1.11

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains defaults through complete calls and contrasts them with *args, but stops short of implementation internals.
Examples
Demonstrates greetings, XML generation with optional content, and summation with an optional starting point.
What it assumes
Assumes familiarity with writing functions and arguments, while demonstrating optional-argument syntax through practical examples.
What you can do after
Build it from scratch in Python by defining optional values and choosing defaults instead of accepting arbitrary arguments.
How it connects
Connects default parameters with functions, *args, keyword arguments, **kwargs, and flexible interfaces.

Also explained in

Compare how 20 books explain default value →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.