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

  • Method Overloading

    Python does not support traditional method overloading in the way languages like C++ or Java do. If you define multiple methods with the same name, the last definition will simply overwrite all previous ones. However, you can achieve the same result—making a single method behave differently based on the number or type of arguments—using Python’s…

  • Python Comments Tutorial: Single-line, Multi-line & Docstrings

    Comments in Python are lines of text within your code that are ignored by the Python interpreter. They are non-executable statements meant to provide explanations, documentation, or clarifications to yourself and other developers who might read your code. Types of Comments Uses of Comments Best Practices Example Python By using comments effectively, you can make…

  • The print() Function in Python

    The print() Function in Python: Complete Guide The print() function is Python’s built-in function for outputting data to the standard output (usually the console). Let’s explore all its arguments and capabilities in detail. Basic Syntax python print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False) Arguments Explained 1. *objects (Positional Arguments) The values to print. You can pass multiple items separated by commas. Examples:…

  • Mathematical Functions

    1. abs() Syntax: abs(x)Description: Returns the absolute value (non-negative value) of a number. Examples: python # 1. Basic negative numbers print(abs(-10)) # 10 # 2. Positive numbers remain unchanged print(abs(5.5)) # 5.5 # 3. Floating point negative numbers print(abs(-3.14)) # 3.14 # 4. Zero remains zero print(abs(0)) # 0 # 5. Complex numbers (returns magnitude) print(abs(3 +…

  • (?),Greedy vs. Non-Greedy, Backslash () ,Square Brackets [] Metacharacters

    The Question Mark (?) in Python Regex The question mark ? in Python’s regular expressions has two main uses: 1. Making a Character or Group Optional (0 or 1 occurrence) This is the most common use – it makes the preceding character or group optional. Examples: Example 1: Optional ‘s’ for plural words python import re pattern…

  • Random Module?

    What is the Random Module? The random module in Python is used to generate pseudo-random numbers. It’s perfect for: Random Module Methods with Examples 1. random() – Random float between 0.0 and 1.0 Generates a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive). python import random # Example 1: Basic random float print(random.random()) # Output: 0.5488135079477204 # Example…

Leave a Reply

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