Intermediate Python for Developers
George Boorman
Curriculum Manager
def average(values): # Calculate the average average_value = sum(values) / len(values) # Return the rounded results return round(average_value, 2)
# Using six arguments average(15, 29, 4, 13, 11, 8)
TypeError: average() takes 1 positional argument but 6 were given
Docstrings help clarify how to use custom functions
Arbitrary arguments allow functions to accept any number of arguments
# Allow any number of positional, non-keyword arguments
def average(*args):
# Function code remains the same
Conventional naming: *args
Allows a variety of uses while producing expected results!
# Calling average with six positional arguments
average(15, 29, 4, 13, 11, 8)
13.33
*
: Convert arguments to a single iterable (tuple)# Calculating across multiple lists
average(*[15, 29], *[4, 13], *[11, 8])
13.33
# Use arbitrary keyword arguments def average(**kwargs):
average_value = sum(kwargs.values()) / len(kwargs.values()) rounded_average = round(average_value, 2) return rounded_average
Arbitrary keyword arguments: **kwargs
keyword=value
# Calling average with six kwargs
average(a=15, b=29, c=4, d=13, e=11, f=8)
13.33
# Calling average with one kwarg
average(**{"a":15, "b":29, "c":4, "d":13, "e":11, "f":8})
13.33
# Calling average with three kwargs
average(**{"a":15, "b":29}, **{"c":4, "d":13}, **{"e":11, "f":8})
13.33
Intermediate Python for Developers