- Author

- Name
- Nelson Silva
- Social
Introduction
When creating functions in Python, we sometimes encounter situations where certain parameters have values that are common or expected by default. To accommodate this without burdening the caller, we use default arguments.
Characteristics of Default Arguments
- Flexibility: They allow a function to be called with fewer arguments than it was defined with.
- Readability: They make the code easier to read and understand, since they show the default values directly in the function definition.
- Error prevention: They ensure the function always has a value to operate with, even if nothing is provided.
How to Use Default Arguments
Defining a default value for an argument is quite straightforward. Simply assign the value in the function definition.
Simple Example
def doorState(state = True):
if state:
print('The door is open.')
else:
print('The door is closed.')
doorState(False) # The door is closed.
But what if we want to use more than one default argument?
Advanced Example
Let's say we have a function that prints information about a book.
def bookInfo(title, author = "Unknown", year = 2020):
print(f"Title: {title}")
print(f"Author: {author}")
print(f"Publication Year: {year}")
bookInfo("Python for Beginners")
# Title: Python for Beginners
# Author: Unknown
# Publication Year: 2020
Here, if the user does not provide the author or the year, the function will use the default values defined.
Conclusion
Default arguments are a powerful tool in Python that increase the adaptability and efficiency of functions. They simplify function calls and help prevent errors caused by omitting arguments.