Python

Python Optional Arguments Defined in Functions

In Python programming, optional arguments within function definitions introduce diversity to parameter handling. This aspect allows the developers to create functions that accommodate multiple inputs, increasing the code versatility. Unlike mandatory parameters, optional arguments come with default values, allowing the flexibility of omitting specific inputs during function calls. This refines the code structure and facilitates an effortless adaptation to diverse scenarios.

Example 1: Basic Usage of Optional Arguments

Before looking into examples, let’s establish a foundational understanding of optional arguments. In Python, a function can be defined with parameters that may have default values, making them optional during the function call. This empowers the developers to create functions that can adapt to various application scenarios without compromising the clarity in the code.

def greet(name, greeting="Hello"):
    """
    A simple function demonstrating the use of an optional argument.
   
    Parameters:
        name (str): The name of the person.
        greeting (str): The greeting message. Default is "
Hello".
    "
""
    print(f"{greeting}, {name}!")

greet("Alice")  
greet("Bob", "Good morning")

 

In this example, we define a “greet” function that takes two parameters – “name” and
“greeting”. The “greeting” parameter is optional with a default value of “Hello”. When the function is called if a value for “greeting” is provided, it uses that value. Otherwise, it defaults to “Hello”. This flexibility allows for appropriate function calls while maintaining a clear and readable function definition.

Example 2: Multiple Optional Arguments

Here, for example, the “describe_person” function demonstrates the use of multiple optional arguments. Both “age” and “occupation” have default values of “None”, making them optional during function call. The function strongly constructs a description based on the provided values, ensuring that only the relevant information is included in the output.

def describe_person(name, age=None, occupation=None):
    """
    A function demonstrating multiple optional arguments.
   
    Parameters:
        name (str): The name of the person.
        age (int): The age of the person. Default is None.
        occupation (str): The occupation of the person. Default is None.
    "
""
    description = f"{name} is"
   
    if age is not None:
        description += f" {age} years old"
   
    if occupation is not None:
        description += f", and works as a {occupation}"
   
    print(description + ".")

# Example usage:
describe_person("Alice")  
describe_person("Bob", 30)  
describe_person("Charlie", occupation="software engineer")

 

Example 3: Mixing the Mandatory and Optional Arguments

This example illustrates a function’s effortless combination of mandatory and optional arguments. The “calculate_total_price” function requires the “item” and “price” as mandatory parameters, while “tax_rate” is optional with a default value of 0.1. Users can choose to specify the tax rate, and the default value is used if it is not provided.

def calculate_total_price(item, price, tax_rate=0.1):
    """
    A function combining mandatory and optional arguments.
   
    Parameters:
        item (str): The name of the item.
        price (float): The base price of the item.
        tax_rate (float): The tax rate. Default is 0.1.
    "
""
    total_price = price + (price * tax_rate)
    print(f"The total price for {item} is ${total_price:.2f}")
calculate_total_price("Laptop", 800)  
calculate_total_price("Camera", 500, 0.05)

 

Example 4: Handling Lists as Optional Arguments

In this example, we explore the “display_items” function that effectively utilizes the optional arguments to handle a variable number of items in a list. The function also introduces the concept of a separator which allows the users to customize the formatting of the displayed items. The “display_items” function is defined with two parameters: “*items” and “separator”. The “*items” parameter is used with an asterisk which indicates that it can accept a variable number of arguments as a tuple. The “separator” parameter is an optional argument that specifies the character that is used to separate the items in the final display. Its default value is “”, “”.

def display_items(*items, separator=", "):
    """
    A function using *args to handle a variable number of items.
   
    Parameters:
        *items (str): Variable number of items.
        separator (str): The separator for displaying items. Default is "
, ".
    "
""
    formatted_items = separator.join(items)
    print(f"Items: {formatted_items}")

display_items("Apple", "Banana", "Orange")  
display_items("Laptop", "Mouse", "Keyboard", separator=" | ")

 

To handle a variable number of items, the use of “*items” allows the function to accept any number of string arguments, forming a tuple named “items”. This flexibility enables the users to provide one or more items during function call. Then the “join” method combines the items in the tuple using the specified “separator”. This results in a formatted string that combines the items into a readable format. The formatted string is then printed, displaying the items clearly and structured. The output string includes the “Items:” label followed by the combined and formatted items.

This example demonstrates the practical use of optional arguments in handling a variable number of items. Users can call the function with different sets of items, and the optional “separator” argument provides a customizable way to format the output. The function is designed to allow for precise and adaptable code, displaying the utility of optional arguments in enhancing the flexibility and expression of Python functions.

Example 5: Combining the Optional Arguments with Default Values

This example has the “create_person_info” function, the “age”, and “address” with the use of “**kwargs” to handle the combination of traditional optional “name” arguments and additional key-value pairs. This allows for a highly flexible function that is capable of handling various information about a person. The function builds a dictionary with the provided information and any extra key-value pairs are passed through “**kwargs”.

def create_person_info(name, age=None, address=None, **kwargs):
    """
    A function combining optional arguments with **kwargs.
   
    Parameters:
        name (str): The name of the person.
        age (int): The age of the person. Default is None.
        address (str): The address of the person. Default is None.
        **kwargs: Additional key-value pairs for any extra information.
    "
""
    person_info = {
        "Name": name,
        "Age": age,
        "Address": address,
    }
    person_info.update(kwargs)
   
    print("Person Information:")
    for key, value in person_info.items():
        print(f"{key}: {value}")
create_person_info("Alice")  
create_person_info("Bob", age=30, city="Wonderland")

 

Example 6: Dynamic Function with Optional Arguments

This example introduces a dynamic function, “generate_sequence”, which generates a sequence of numbers given a start, end, and optional step size. The “step” parameter is optional with the default value that is set to 1 if not specified. This demonstrates how the optional arguments can be employed to create functions that adapt to different scenarios, providing a customizable user experience.

def generate_sequence(start, end, step=1):
    """
    A function generating a sequence of numbers with optional step size.
   
    Parameters:
        start (int): The starting value of the sequence.
        end (int): The ending value of the sequence.
        step (int): The step size between numbers. Default is 1.
    "
""
    sequence = list(range(start, end + 1, step))
    print(f"Generated Sequence: {sequence}")

generate_sequence(1, 10)  
generate_sequence(0, 20, 2)

 

Example 7: File Handling with Optional Arguments

To handle the file with optional arguments, this example demonstrates a file-handling function which is “read_file” with optional arguments to specify the file mode and encoding. The function reads the content of a file. If the file is not found, it simply handles the exception. The optional arguments allow the users to read the files with different modes and encodings, displaying the practicality of optional arguments in real-world scenarios.

def read_file(file_path, mode="r", encoding="utf-8"):
    """
    A function for reading a file with optional mode and encoding.
   
    Parameters:
        file_path (str): The path to the file.
        mode (str): The file mode (e.g., 'r' for read). Default is 'r'.
        encoding (str): The file encoding. Default is 'utf-8'.
    "
""
    try:
        with open(file_path, mode, encoding=encoding) as file:
            content = file.read()
            print(f"File Content: {content}")
    except FileNotFoundError:
        print(f"File not found at path: {file_path}")

read_file("sample.txt")  
read_file("nonexistent.txt", mode="w")

 
Output:

Example 8: Building a Custom Calculator with Python Optional Arguments

Let’s do another example to create a customizable calculator in Python, utilizing the power of optional arguments to enhance its functionality. Our calculator handles the basic arithmetic operations which allow the users to customize the precision of results and choose the mathematical operation that they want to perform.

First, the “custom_calculator” function is defined with four parameters which are “num1”, “num2”, “operation”, and “precision”. The “num1” and “num2” represent the operands for arithmetic operations. The “operation” is an optional argument that determines the mathematical operation to perform. It defaults to addition “add”. The “precision” is an optional argument that defines the decimal precision of the result with a default value of 2.

def custom_calculator(num1, num2, operation="add", precision=2):
    """
    A customizable calculator supporting basic arithmetic operations.
   
    Parameters:
        num1 (float): The first operand.
        num2 (float): The second operand.
        operation (str): The mathematical operation. Default is 'add'.
        precision (int): The decimal precision of the result. Default is 2.
    "
""
    result = 0
   
    if operation == "add":
        result = num1 + num2
    elif operation == "subtract":
        result = num1 - num2
    elif operation == "multiply":
        result = num1 * num2
    elif operation == "divide":
        if num2 != 0:
            result = num1 / num2
        else:
            print("Error: Division by zero is not allowed.")
            return
   
    formatted_result = round(result, precision)
    print(f"Result of {operation.capitalize()}: {formatted_result}")
# Addition
custom_calculator(5, 3)  
# Multiplication with custom precision
custom_calculator(7, 4, operation="multiply", precision=3)  

# Division with error handling
custom_calculator(10, 0, operation="divide")

 
Output:

The function employs the conditional statements for arithmetic operations to determine the operation that is specified by the “add”, “subtract”, “multiply”, or “divide” user. The respective arithmetic operation is executed based on the specified or default operation. The formatted result is then displayed, providing a clear and precise output. A conditional check ensures that the divisor (num2) is not zero before performing the division to prevent the division by zero errors.

Conclusion

Python’s optional arguments in function definitions provide a versatile system for creating an adaptable and readable code. From its basic usage with default values to handling the variable numbers of arguments and including the additional key-value pairs, the examples that are presented demonstrate Python’s flexibility and expression. Understanding and effectively utilizing the optional arguments can significantly enhance a developer’s ability to design the functions which contributes to the overall maintainability of the Python code.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.