Skip to main content

How to Give a Function Parameter a Default Value in Python

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Some function arguments have a value that's right most of the time. Give that parameter a default in the def line, and callers can leave it out or pass their own value. This guide writes a greeting function with a default greeting, with real output from Python 3.15.2.

Syntax​

Syntax
def <function>(<parameter>, <parameter with default>=<default value>):
...
PartWhat it means
<parameter>Required: every call must pass it
<parameter with default>=<default value>Optional: when a call leaves it out, it gets <default value>. Parameters with defaults come after the ones without

The Python tutorial: "The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow."

Prerequisites​

  • uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

default_param.py
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"


print(greet("Ada"))
print(greet("Ada", "Welcome"))

The default_param.py script in a macOS-style code window: def greet(name, greeting="Hello") returning the greeting and name, then print(greet("Ada")) and print(greet("Ada", "Welcome")).

Step 2: Run It​

Terminal
uv run python default_param.py
Output
Hello, Ada!
Welcome, Ada!

The script's output in a terminal: Hello, Ada! and Welcome, Ada!

The first call left greeting out and got "Hello"; the second passed "Welcome" instead.

Common Mistakes​

MistakeWhat happensDo this instead
A parameter without a default after one with itdef greet(greeting="Hello", name): raised SyntaxError: parameter without a default follows parameter with a defaultPut the required parameters first
A list as the defaultOne list is shared by every call: add_item("apple") gave ['apple'], then add_item("pear") gave ['apple', 'pear']Default to None and make the list inside: the same calls gave ['apple'] and ['pear']

Troubleshooting​

SymptomLikely causeFix
A default list or dictionary keeps values from earlier callsThe default is made once, when the function is definedUse None as the default and create the list in the function

FAQ​

When is the default value made?​

Once, when Python runs the def line. The tutorial: "Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes."

Can a call name the parameter?​

Yes: greet("Ada", greeting="Welcome") passes it by name, which reads clearly when a function has several defaults.

Conclusion​

greeting="Hello" made the second parameter optional: greet("Ada") said Hello, Ada! and greet("Ada", "Welcome") said Welcome, Ada!. Keep required parameters first, and use None instead of a list as a default.

Additional Resources​