How to use default method parameters in Python

1 min readFundamentalsFunctionsBuilt-in
7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

In Python, you can make default method parameters by assigning a value to the parameter when it's defined in the function signature. For example, the following function has a default parameter x with a value of 0:

def my_function(x=0):
    return x

When the function is called without any arguments, the value of x is set to 0. If you pass a value to the function, that value will be used instead:

>>> my_function()
0
>>> my_function(5)
5

You can also assign default parameters to multiple parameters in the function signature as

def my_function(x=0, y=1, z=2):
    return x, y, z

When the function is called without any arguments, the value of x, y and z will be set to 0, 1, 2 respectively. If you pass values to the function, the respective values will be used instead:

>>> my_function()
(0, 1, 2)
>>> my_function(5,6,7)
(5, 6, 7)

It's worth noting that default parameters must be placed at the end of the parameter list. If you have a non-default parameter followed by a default parameter, you will get a SyntaxError.

7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

Master Data Science in Days, Not Months 🚀

Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.