Functions

  • Define with def
  • Code block defined by indentation as per loops.
  • Use return keyword to return a value.
  • If return is not specified, None is returned.
def multiply(x, y):
    return x * y

result = multiply(12, 12)
print(result)

Parameters

  • Required
  • Optional
  • Must define required before optional.
  • Variables defined in the function are local scope.
  • Optional parameters are configured with a default value in the function definition
def multiply(x, y = 2):
    return x * y

result = multiply(12)
print(result)
  • Writing to a global variable in a function requires explicitly specifing it's use with theglobal keyword
x = 100

def func():
    global x
    x += 10
    print(x)

Named arguments

  • Function can be called with named arguments to improve code readability.
teams = [
    {"name": "888", "bossman": "Rolly", "car": "ZB"},
    {"name": "Erebus", "Bossman": "Betty", "Car": "ZB"}
    {"name": "WAU", "Bossman": "Ryan", "Car": "ZB"}
    {"name": "DLR Team Penske", "Bossman": "The Captain", "Car": "Mustang"}
]

def add_team(name, manager, car):
    team = {"name": name, "bossman": manager, "car": car}
    teams.append(team)


add_team(name="BJR", manager="Brad", car="ZB")

KWArgs

  • Key/word arguments.
  • Allow passing on unspecified number of arguments.
  • Referenced by the keyword used in the function call.
def print_team(name, **kwargs):
    print(name)
    print(kwargs["manager"], kwargs["car"])

print_team("BJR", manager="Brad", car="ZB")

Nested Functions

  • A function can be defined inside another function
  • Useful if you want to reduce repetition but inner function specific to outer function
  • Inner function has access to outer function local variable
  • Unsure how often you would do this in reality.

Built-in Functions

len("How long is this string?")
str("888")  # Is now a string
int("888")  # Is now an int
float("3.14") # Is now a float
input # get raw input from console.

Input function

  • Allows input from console.
  • Obviously wrap some validation around any user supplied data.
  • Execution stops while waiting for input.
def add_team(name, manager, car):
    team = {"name": name, "bossman": manager, "car": car}
    teams.append(team)


team_name = input("Enter team name: ")
manager = input("Enter team manager: ")
car = input("Enter team car: ")
add_team(team_name, manager, car)

Docstrings

  • Explain the purpose of a function
  • Used to define what data type each parameter needs to be.
  • Can use the help command to extract docstrings.
def multiply(x, y):
    """
    Return x * y.
    :param x: int.
    :param y: int.
    :return: int result of multipling x * y
    """
    return x * y

help(multiply)