Python Functions


A Python function is a named block of reusable code.

  • Syntax def name(parameters):
  • parameters are input values passed to the function
  • can return a value

Create a Function

A Python function is defined using the def keyword, followed by a function name, parentheses (), and a colon :.

  • pass statement is a placeholder that does nothing
def function_name():
    # function body
    pass

Calling a Function

  • call it with its name and ()
def function_name():
    # function body
    pass
 
# Call the function
function_name()

Arguments

Arguments in Python are values that are passed to a function when it is called.

  • each argument is treated as a variable in the function
  • used to provide inputs
def add_device(network_devices, device):
    network_devices.add(device)
    return network_devices

Parameters vs Arguments

Parameters are variables in a function’s definition.

  • initialize with arguments

Arguments are actual values passed to a function.

Both terms are often used interchangeably in discussions about functions.

Arbitrary Arguments

Arbitrary arguments in Python allow a function to accept any number of arguments.

  • useful when the exact number of arguments is not known in advance
  • defined by prefixing the argument name with an asterisk * in the function definition
  • use loops and in keyword to access arguments
def function_name(*args):
    for arg in args:
        print(arg)
  • In this case, args is a tuple of all the arguments passed to the function
  • function prints each argument

Keyword Arguments

Keyword arguments in Python are arguments that are identified by the parameter name in a function call.

  • caller identifies the arguments by the parameter name
    • allows for the arguments to be passed in any order
    • makes the function call more clear
def function_name(keyword1=value1, keyword2=value2):
    # function body
    pass

Arbitrary Keyword Arguments

Arbitrary keyword arguments in Python allow a function to accept any number of keyword arguments.

  • useful when the exact number of keyword arguments is not known in advance
  • defined by prefixing the argument name with a double asterisk ** in the function definition
def function_name(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

Example

Consider a function that configures a network device with arbitrary settings:

def configure_device(**settings):
    for setting, value in settings.items():
        print(f"Setting {setting} to {value}")

 - settings is a dictionary of all the settings for the device
 - The function prints each setting and its value
 - function can be called with arbitrary keyword arguments:
 - configure_device(ip_address='192.168.1.1', subnet_mask='255.255.255.0', gateway='192.168.1.254')

Default Parameter Values

A default parameter value in Python is a value that is assigned to a function parameter when the function is defined.

  • if no argument is called for the parameter, then the default is used
  • specified by using the assignment operator + in the function definition
def function_name(parameter='default value'):
    # function body
    pass

Passing a List as an Argument

  • can pass a list as an argument
def function_name(list_parameter):
    for item in list_parameter:
        print(item)

Returning a Value

A Python function returns a value using the return statement.

  • if no value is specified, function returns None
def function_name():
    return 'value'

Function Recursion

Function recursion in Python is a process in which a function calls itself as a subroutine.

  • allows the function to be repeated several times
  • can be:
    • direct
      • occurs if a function calls itself
    • indirect
      • involves the function calling another function, which eventually calls the original function
def countdown(n):
    if n <= 0:
        print('Liftoff!')
    else:
        print(n)
        countdown(n-1)