5: Advanced Functions

Summary

  • You can call functions using parameters as keyword parameters or positional parameters

  • Python allows you to set defaults for parameters

  • You can force parameters yo be positional only or keyword only using / and *

  • Specifying *name is a way of using a variable number of positional parameters
    • Any arguments supplied that are not used by positional parameters are stored in *name asa tuple

  • Specifying **kwname works in the same way as *name but any unused keyword arguments are stored in it as a dictionary

  • You can pass parameters as tuples or dictionaries by using the unpacking operators * and **

  • Functions can return multiple values by returning a tuple which czn be unpacked into variables using destructuring assignment

  • Docstrings can be used to create rudimentary documentation for a function

  • Annotations can be applied to parameters and return values, usually to indicate the type

Program

GLOBAL_TAX = 0.10  # global variable


def calculate_total(price: float, /, quantity: int = 1, *, discount: float = 0.0, **extras) -> tuple:
    """
    Calculates the final total for a purchase.

    price: item price (positional-only)
    quantity: number of items (default = 1)
    discount: discount percentage (keyword-only)
    **extras: extra keyword arguments
    """

    subtotal = price * quantity
    discount_amount = subtotal * discount
    tax = subtotal * GLOBAL_TAX
    total = subtotal - discount_amount + tax

    print("Extras received (stored as dictionary):", extras)

    return subtotal, total  # returning multiple values


def add_numbers(*numbers: float) -> float:
    """
    Adds any number of positional arguments.
    """
    print("Numbers received (stored as tuple):", numbers)
    return sum(numbers)


# -------------------------
# Using the functions
# -------------------------

# Calling with positional + keyword arguments
sub, total = calculate_total(20.0, quantity=2, discount=0.1, gift_wrap=True)
print("Subtotal:", sub)
print("Total:", total)

# Using *args
print("Sum:", add_numbers(1, 2, 3))

# Unpacking tuple and dictionary into function
values = (15.0,)
options = {"quantity": 3, "discount": 0.05}

sub2, total2 = calculate_total(*values, **options)
print("Second Total:", total2)

Program Output

(docs-env) root@BMitchellLTOP:~/git/sphinx_students/source/programming_lang/book/programs# python3 chapterFive.py
Extras received (stored as dictionary): {'gift_wrap': True}
Subtotal: 40.0
Total: 40.0
Numbers received (stored as tuple): (1, 2, 3)
Sum: 6
Extras received (stored as dictionary): {}
Second Total: 47.25