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

  • Basic Character Classes

    Basic Character Classes Pattern Description Example Matches [abc] Matches any single character in the brackets a, b, or c [^abc] Matches any single character NOT in the brackets d, 1, ! (not a, b, or c) [a-z] Matches any character in the range a to z a, b, c, …, z [A-Z] Matches any character in the range A to Z A, B, C, …, Z [0-9] Matches…

  • Keyword-Only Arguments in Python and mixed

    Keyword-Only Arguments in Python Keyword-only arguments are function parameters that must be passed using their keyword names. They cannot be passed as positional arguments. Syntax Use the * symbol in the function definition to indicate that all parameters after it are keyword-only: python def function_name(param1, param2, *, keyword_only1, keyword_only2): # function body Simple Examples Example 1: Basic Keyword-Only Arguments…

  • Special Character Classes Explained with Examples

    Special Character Classes Explained with Examples 1. [\\\^\-\]] – Escaped special characters in brackets Description: Matches literal backslash, caret, hyphen, or closing bracket characters inside character classes Example 1: Matching literal special characters python import re text = “Special chars: \\ ^ – ] [” result = re.findall(r'[\\\^\-\]]’, text) print(result) # [‘\\’, ‘^’, ‘-‘, ‘]’] # Matches…

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

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

  •  Duck Typing

    Python, Polymorphism allows us to use a single interface (like a function or a method) for objects of different types. Duck Typing is a specific style of polymorphism common in dynamically-typed languages like Python. What is Duck Typing? 🦆 The name comes from the saying: “If it walks like a duck and it quacks like…

Leave a Reply

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