0
0
Pythonprogramming~5 mins

Default arguments in Python

Choose your learning style9 modes available
Introduction

Default arguments let you give a function a value to use if no value is provided. This makes your functions easier to use and avoids errors.

When you want a function to work even if some inputs are missing.
When you want to set common values that usually don't change.
When you want to avoid writing extra code to check if a value was given.
When you want to make your function flexible for different situations.
Syntax
Python
def function_name(parameter1=default_value1, parameter2=default_value2):
    # function body

Default values are set using the equals sign (=) after the parameter name.

Parameters with default values should come after parameters without defaults.

Examples
This function says hello to the given name. If no name is given, it uses "friend".
Python
def greet(name="friend"):
    print(f"Hello, {name}!")
This function returns the base raised to the exponent. If exponent is not given, it squares the base.
Python
def power(base, exponent=2):
    return base ** exponent
This function describes a pet. If the animal type is not given, it assumes a dog.
Python
def describe_pet(pet_name, animal_type="dog"):
    print(f"I have a {animal_type} named {pet_name}.")
Sample Program

This program shows how the greet function works with and without giving a name.

Python
def greet(name="friend"):
    print(f"Hello, {name}!")

greet()
greet("Alice")
OutputSuccess
Important Notes

Default arguments are evaluated once when the function is defined, not each time it is called.

Be careful when using mutable default arguments like lists or dictionaries.

Summary

Default arguments let functions have optional inputs with preset values.

They make functions easier to use and more flexible.

Always put parameters with defaults after those without.