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

  • re.split()

    Python re.split() Method Explained The re.split() method splits a string by the occurrences of a pattern. It’s like the built-in str.split() but much more powerful because you can use regex patterns. Syntax python re.split(pattern, string, maxsplit=0, flags=0) Example 1: Splitting by Multiple Delimiters python import retext1=”The re.split() method splits a string by the occurrences of a pattern. It’s like…

  • sqlite3 create table

    The sqlite3 module is the standard library for working with the SQLite database in Python. It provides an interface compliant with the DB-API 2.0 specification, allowing you to easily connect to, create, and interact with SQLite databases using SQL commands directly from your Python code. It is particularly popular because SQLite is a serverless database…

  • 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…

  • List of machine learning libraries in python

    Foundational Libraries: General Machine Learning Libraries: Deep Learning Libraries: Other Important Libraries: This is not an exhaustive list, but it covers many of the most important and widely used machine learning libraries in Python. The choice of which library to use often depends on the specific task at hand, the size and type of data,…

  •  List operators,List Traversals

    In Python, lists are ordered, mutable collections that support various operations. Here are the key list operators along with four basic examples: List Operators in Python 4 Basic Examples 1. Concatenation (+) Combines two lists into one. python list1 = [1, 2, 3] list2 = [4, 5, 6] combined = list1 + list2 print(combined) # Output: [1, 2, 3,…

Leave a Reply

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