Default Arguments

A default argument gives a parameter a value when the caller does not provide one.

Now both calls work:

Output:

Hello, Ada
Welcome, Ada

Why Defaults Help

Defaults are useful when one value is common but sometimes needs to change.

Example:

Calling scale(8) leaves the value unchanged. Calling scale(8, 3) multiplies by 3.

A simple default

The same function can use its default or an explicit argument.

Runs locally with Python in your browser.

Ready to run.

Keyword Arguments

You can name an argument at the call site:

print(scale(value=8, factor=3))

Keyword arguments make calls clearer when several values have similar types.

Later, you will see calls like:

plot_loss(values, title="Training loss")

The keyword explains the role of the argument.

Keep Defaults Simple

Use simple immutable defaults such as numbers, strings, booleans, or None.

Avoid advanced default patterns for now. In this course, defaults should make small functions easier to call, not clever.

Required Parameters Come First

Putting a required parameter after a default parameter is invalid:

Required parameters should come first:

Exercise: Use the default

What does this print?

Compute it first, then check your number.

HintFill the missing argument

The call supplies value=5 but no factor, so use the value written in the function definition.

SolutionThe default doubles five

factor uses its default value 2. The return expression becomes 5 * 2, so the function returns 10.

Defaults Should Be Stable Choices

Defaults reduce repetition. Use them when there is a clear common value and the function remains easy to read.