Default Arguments

Default Arguments in Python Functions

Default arguments allow you to specify default values for function parameters. If a value isn’t provided for that parameter when the function is called, Python uses the default value instead.

Basic Syntax

python

def function_name(parameter=default_value):
    # function body

Simple Examples

Example 1: Basic Default Argument

python

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

# Using the function
greet("Alice")      # Output: Hello, Alice!
greet()             # Output: Hello, Guest!

Example 2: Multiple Default Arguments

python

def order_food(item="pizza", quantity=1):
    print(f"Order: {quantity} {item}(s)")

order_food("burger", 2)    # Output: Order: 2 burger(s)
order_food("pasta")        # Output: Order: 1 pasta(s)
order_food()               # Output: Order: 1 pizza(s)

Example 3: Mixing Regular and Default Arguments

python

def calculate_area(length, width=10):
    area = length * width
    print(f"Area: {area} square units")

calculate_area(5, 3)    # Output: Area: 15 square units
calculate_area(5)       # Output: Area: 50 square units

Example 4: Practical Use Case

python

def create_user_profile(name, age, country="Unknown"):
    print(f"Name: {name}")
    print(f"Age: {age}")
    print(f"Country: {country}")
    print("-" * 20)

create_user_profile("John", 25, "USA")
create_user_profile("Sarah", 30)  # Country will be "Unknown"

Important Rules

  1. Default arguments must come after non-default arguments:

python

# Correct:
def func(a, b=10):
    pass

# Wrong:
# def func(a=10, b):  # This will cause an error
#     pass
  1. Default values are evaluated only once when the function is defined:

python

def add_item(item, shopping_list=[]):
    shopping_list.append(item)
    return shopping_list

print(add_item("apple"))    # Output: ['apple']
print(add_item("banana"))   # Output: ['apple', 'banana']

Best Practice for Mutable Default Arguments

For lists, dictionaries, or other mutable objects, it’s better to use None as the default:

python

def add_item_better(item, shopping_list=None):
    if shopping_list is None:
        shopping_list = []
    shopping_list.append(item)
    return shopping_list

print(add_item_better("apple"))    # Output: ['apple']
print(add_item_better("banana"))   # Output: ['banana']

Key Benefits

  • Flexibility: Functions can be called with fewer arguments
  • Readability: Makes function calls cleaner when many parameters have common values
  • Backward compatibility: You can add new parameters without breaking existing code

Default arguments make your functions more versatile and user-friendly!

Similar Posts

  • Linear vs. Scalar,Homogeneous vs. Heterogeneous 

    Linear vs. Scalar Data Types in Python In programming, data types can be categorized based on how they store and organize data. Two important classifications are scalar (atomic) types and linear (compound) types. 1. Scalar (Atomic) Data Types 2. Linear (Compound/Sequential) Data Types Key Differences Between Scalar and Linear Data Types Feature Scalar (Atomic) Linear (Compound) Stores Single…

  • Escape Sequences in Python

    Escape Sequences in Python Regular Expressions – Detailed Explanation Escape sequences are used to match literal characters that would otherwise be interpreted as special regex metacharacters. 1. \\ – Backslash Description: Matches a literal backslash character Example 1: Matching file paths with backslashes python import re text = “C:\\Windows\\System32 D:\\Program Files\\” result = re.findall(r'[A-Z]:\\\w+’, text) print(result) #…

  • Dictionaries

    Python Dictionaries: Explanation with Examples A dictionary in Python is an unordered collection of items that stores data in key-value pairs. Dictionaries are: Creating a Dictionary python # Empty dictionary my_dict = {} # Dictionary with initial values student = { “name”: “John Doe”, “age”: 21, “courses”: [“Math”, “Physics”, “Chemistry”], “GPA”: 3.7 } Accessing Dictionary Elements…

  • Variable Length Positional Arguments in Python

    Variable Length Positional Arguments in Python Variable length positional arguments allow a function to accept any number of positional arguments. This is done using the *args syntax. Syntax python def function_name(*args): # function body # args becomes a tuple containing all positional arguments Simple Examples Example 1: Basic *args python def print_numbers(*args): print(“Numbers received:”, args) print(“Type of…

  • Unlock the Power of Python: What is Python, History, Uses, & 7 Amazing Applications

    What is Python and History of python, different sectors python used Python is one of the most popular programming languages worldwide, known for its versatility and beginner-friendliness . From web development to data science and machine learning, Python has become an indispensable tool for developers and tech professionals across various industries . This blog post…

Leave a Reply

Your email address will not be published. Required fields are marked *