- __init__() function
- Aliases
- and operator
- argparse
- Arrays
- Booleans
- Break statement
- Bytes
- Classes
- Closure
- Code blocks
- Comments
- Conditional statements
- Console
- Context manager
- Data class
- Data structures
- Data types
- Data visualization
- datetime module
- Decorator
- Dictionaries
- Dictionary comprehension
- Django
- Docstrings
- Encapsulation
- enum
- enumerate() function
- Equality operator
- Error handling
- Exception handling
- False
- File handling
- Filter()
- Flask framework
- Floats
- Floor division
- For loops
- Formatted strings
- Functions
- Generator
- Globals()
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Inheritance
- Integers
- Iterator
- Lambda function
- len() Function
- Less than operator
- Less than or equal to operator
- List append() method
- List comprehension
- List count()
- List insert() method
- List pop() method
- List reverse() method
- List sort() method
- Lists
- Logging
- map() function
- Match statement
- Math module
- Merge sort
- Min()
- Modules
- Modulo operator
- Multiline comment
- Multiprocessing
- Multithreading
- None
- not operator
- NumPy library
- OOP
- Optional arguments
- or operator
- Override method
- Pandas library
- Parameters
- pathlib module
- Pickle
- Polymorphism
- print() function
- Property()
- Protocol
- Random module
- range() function
- Raw strings
- Recursion
- Reduce()
- Regular expressions
- requests Library
- return statement
- round() function
- Script
- Set comprehension
- Sets
- SQLite
- String decode()
- String find()
- String join() method
- String replace() method
- String split() method
- String strip()
- Strings
- Ternary operator
- time.sleep() function
- True
- try...except statement
- Tuples
- Type casting
- Variables
- Virtual environment
- What is Python?
- While loops
- yield
- Zip function
PYTHON
Python Optional Argument: Syntax, Usage, and Examples
An optional argument in Python is a function parameter that has a default value, so you can call the function with or without passing that value. Optional arguments help you write cleaner function calls while keeping your code flexible.
How to Use an Optional Argument in Python
You create an optional argument by assigning a default value in the function definition. If the caller doesn’t pass that argument, Python uses the default.
Learn Python on Mimo
Basic syntax
Python
defgreet(name, punctuation="!"):
print("Hello, " + name + punctuation)
greet("Mina")# Hello, Mina!
greet("Mina","?")# Hello, Mina?
In this function:
nameis a required argumentpunctuationis an optional argument because it has a default value
Optional arguments go after required arguments
Python requires that parameters with defaults come last.
✅ Valid:
Python
defsend_message(text, urgent=False):
print(text, urgent)
❌ Invalid:
Python
defsend_message(urgent=False, text):
print(text, urgent)
If optional arguments appeared first, Python wouldn’t know which values belong to which parameters when calling the function.
Using None as a default
Sometimes you don’t want a “real” default value like 0 or "". In that case, None is a common choice.
Python
defcreate_user(username, nickname=None):
if nicknameisNone:
nickname = username
return {"username": username,"nickname": nickname}
print(create_user("sara"))
print(create_user("sara","s"))
This lets you detect if the caller passed a value or not.
Optional arguments with multiple defaults
A function can have many optional arguments.
Python
deforder_summary(item, quantity=1, include_receipt=True):
message =f"{quantity} x{item}"
if include_receipt:
message +=" (receipt included)"
return message
print(order_summary("coffee"))
print(order_summary("coffee",2))
print(order_summary("coffee",2,False))
This kind of design makes function calls quick for common cases, while still allowing customization.
Keyword arguments make optional arguments easier to read
Optional arguments work best when you use them as keyword arguments. That way, the meaning is obvious.
Python
defschedule_meeting(day, time="10:00", online=True):
returnf"{day} at{time}, online={online}"
print(schedule_meeting("Monday"))
print(schedule_meeting("Monday", time="14:30"))
print(schedule_meeting("Monday", online=False))
You don’t need to remember the parameter order as much, and the call becomes more self-explanatory.
When to Use an Optional Argument
Optional arguments solve a common problem in programming: one function should support simple calls and more advanced calls without forcing every caller to pass the same long list of values.
Here are a few situations where optional arguments are genuinely useful.
1) When a function has a “common default” behavior
A lot of functions have one obvious behavior most of the time.
Example: printing logs to the console by default, but letting you switch it off.
Python
deflog(message, verbose=True):
if verbose:
print("[LOG]", message)
Most calls stay short:
Python
log("Connected")
2) When you want optional configuration without breaking existing code
Optional arguments help you extend a function later without forcing changes everywhere.
Imagine you already have a function:
Python
defsend_email(to, subject):
print("Sending email to", to)
Later, you want to add an optional argument like cc=None:
Python
defsend_email(to, subject, cc=None):
print("Sending email to", to,"cc:", cc)
Older code still works, but new code can use the new feature.
3) When you want your API to feel friendly
Optional arguments can make your functions feel nicer to work with. You can offer a simple call for beginners, and extra switches for people who need more control.
Think of it like ordering pizza.
You can say “one pizza please,” or you can go full mode and choose crust, toppings, and extra cheese. Same pizza shop, different levels of detail.
4) When a function handles different levels of detail
Some inputs are optional because they’re not always known.
Example: a user might not have a phone number.
Python
defsave_contact(name, phone=None):
return {"name": name,"phone": phone}
Examples of Optional Arguments in Python
Let’s walk through a few realistic examples that show optional arguments in action.
Example 1: A function with an optional formatting style
You might want to print prices with or without a currency symbol.
Python
defformat_price(amount, currency="$"):
returnf"{currency}{amount:.2f}"
print(format_price(9.5))# $9.50
print(format_price(9.5,"€"))# €9.50
print(format_price(9.5,"USD "))# USD 9.50
The function works out of the box, but still allows customization.
Example 2: An optional argument for limiting results
Optional arguments show up a lot in search-style functions.
Python
deffind_top_scores(scores, limit=3):
sorted_scores =sorted(scores, reverse=True)
return sorted_scores[:limit]
scores = [88,91,70,99,85,93]
print(find_top_scores(scores))# [99, 93, 91]
print(find_top_scores(scores,2))# [99, 93]
Now the caller can request fewer or more results without needing a second function.
Example 3: Optional “debug mode” in a function
Debug flags are a classic example.
Python
defcalculate_total(prices, debug=False):
total =sum(prices)
if debug:
print("Prices:", prices)
print("Total:", total)
return total
calculate_total([4.5,2.0,3.25])
calculate_total([4.5,2.0,3.25], debug=True)
You keep the normal version clean and quiet, then turn on extra details only when needed.
Example 4: Optional argument with keyword use
Keyword arguments make optional arguments easy to read, especially when there are multiple.
Python
defcreate_profile(name, city="Unknown", show_email=False):
profile = {"name": name,"city": city}
if show_email:
profile["email_visible"] =True
return profile
print(create_profile("Leila"))
print(create_profile("Leila", city="Vienna"))
print(create_profile("Leila", show_email=True))
Notice how you can skip city but still set show_email. That’s one of the biggest advantages of optional arguments.
Example 5: Optional argument with None for “computed defaults”
Sometimes the default depends on the input.
Python
defbuild_username(first_name, last_name, separator=None):
if separatorisNone:
separator ="."
return first_name.lower() + separator + last_name.lower()
print(build_username("Ana","Kovacs"))# ana.kovacs
print(build_username("Ana","Kovacs","_"))# ana_kovacs
This pattern avoids confusing defaults and gives you control when you need it.
Learn More About Optional Arguments
Optional arguments feel simple at first, but a few rules and best practices will save you from tricky bugs later.
Optional argument vs optional parameter
People often say “optional argument,” but the more precise wording is:
- Parameter: the variable in the function definition (
punctuation="!") - Argument: the value you pass into the function (
"?")
In real life, most developers mix the terms, and that’s fine. The key idea is still the same: you don’t have to pass the value every time.
Optional arguments and positional vs keyword calls
You can pass optional arguments by position:
Python
defgreet(name, punctuation="!"):
print("Hello, " + name + punctuation)
greet("Kai","?")
Or by keyword:
Python
greet("Kai", punctuation="?")
Keyword calls are usually easier to read, especially when the argument is a boolean.
Compare these:
Python
save_file("report.txt",True)
save_file("report.txt", overwrite=True)
The second one explains itself.
Be careful with mutable default values
This is the biggest optional argument trap in Python.
If you use a mutable type like a list or dictionary as a default, Python creates it once and reuses it across calls.
❌ Buggy:
Python
defadd_item(item, items=[]):
items.append(item)
return items
print(add_item("a"))
print(add_item("b"))# surprise: ['a', 'b']
The list keeps growing because it’s the same list every time.
✅ Safer pattern:
Python
defadd_item(item, items=None):
if itemsisNone:
items = []
items.append(item)
return items
print(add_item("a"))
print(add_item("b"))# ['b']
Using None and creating a new list inside the function avoids the shared-default problem.
Optional arguments can make APIs clearer, but don’t overdo it
Optional arguments are great, but too many can make a function hard to understand.
If a function has 8 optional arguments, calling it starts to feel like assembling IKEA furniture without the manual.
In that case, you can:
- group related options into a dictionary
- split the function into smaller functions
- use classes to store configuration
How optional arguments interact with *args and **kwargs
You can combine optional arguments with *args and **kwargs when you want extra flexibility.
Python
defsend_alert(message, level="info", **kwargs):
print("Level:", level)
print("Message:", message)
print("Extra:", kwargs)
send_alert("Server down", level="critical", channel="sms", retry=3)
Here:
levelis an optional argument*kwargscollects extra named arguments
This style is common in libraries that want customizable behavior without strict limits.
Summary
An optional argument in Python is a function argument backed by a default value, so the caller can skip it when they want the default behavior. Optional arguments make functions easier to call, easier to extend over time, and more pleasant to work with, especially when paired with keyword arguments and safe defaults like None.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot