How to use default method parameters in Python
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.
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.
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.
Related Articles
Continue your learning journey with these related topics
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. 📚