Home > Articles > Python Functions, Classes, and Modules

Python Functions, Classes, and Modules

Chapter Description

Building Python functions allows for the creation of reusable code and is the first step toward writing object-oriented code. In this sample chapter from Cisco Certified DevNet Associate DEVASC 200-901 Official Cert Guide, you will review working with and building Python functions. It also introduces how Python modules can extend the capabilities of Python and make your job of coding much easier.

Using Arguments and Parameters

An argument is some value (or multiple values) that you pass to a function when you call the function within code. Arguments allow a function to produce different results and make code reuse possible. You simply place arguments within the parentheses after a function name. For example, this example shows how you can pass multiple numeric arguments to the max() function to have it return the largest number in the list:

>>> max(50, 5, 8, 10, 1)
50

Each function must define how it will use arguments, using parameters to identify what gets passed in and how it gets used. A parameter is simply a variable that is used in a function definition that allows code within the function to use the data passed to it. To get results back from the function, you use the keyword return and the object you want to pass back. The following example shows how to create a function that subtracts two numbers and stores the result in a local variable called result that gets returned when the function is called:

>>> def sub(arg1, arg2):
        result = arg1 - arg2
        return result

>>> sub(10, 15)
-5

The variable result is local, meaning that it is not accessible to the main Python script, and it is used only within the function itself. If you tried to call result directly, Python would produce an error saying that result is not defined. You can, however, access global variables from within the function; you might do this, for example, to set certain constants or key variables that any function can use (for example, IP addresses). The difference in accessibility between a local variable and global variable is important, because they allow your code to maintain separation and can keep your functions self-contained.

The previous example uses positional arguments, which must be passed to a function in a particular order. Positional arguments work with a simple set of consistently applied arguments, but if a function needs more flexible alignment to parameters within a function, you can use keyword arguments instead. A keyword argument is a name/value pair that you pass to a function. Instead of using position, you specify the argument the function uses. It is a lot like assigning a variable to an argument. In the previous example, arg1 is subtracted from arg2, and if the positions of these arguments were switched, you would get a different result when subtracting the values. With keyword arguments, it doesn’t matter in what order they are passed to the function. Here is an example:

>>> sub(arg2=15, arg1=10)
-5

What happens if you don’t know the total number of arguments that are being passed to a function? When you read in data, you might not know how many arguments to expect. Python allows you to use * and ** (often referred to as *args and **kwargs) to define any number of arguments or keyword arguments. * and ** allow you to iterate through a list or other collection of data, as shown in this example:

>>> def hello(*args):
        for arg in args:
            print("Hello", arg, "!")

>>> hello('Caleb', 'Sydney', 'Savannah')
Hello Caleb !
Hello Sydney !
Hello Savannah !

By using keyword arguments, you can send a list of key/value pairs to a function, as in the following example:

>>> def hello(**kwargs):
        for key, value in kwargs.items():
            print("Hello", value, "!")

>>> hello(kwarg1='Caleb', kwarg2='Sydney', kwarg3='Savannah')

Hello Caleb !
Hello Sydney !
Hello Savannah !

Note the use of the items() function in the for statement to unpack and iterate through the values.

You can also supply a default value argument in case you have an empty value to send to a function. By defining a function with an assigned key value, you can prevent an error. If the value in the function definition is not supplied, Python uses the default, and if it is supplied, Python uses what is supplied when the function is called and then ignores the default value. Consider this example:

>>> def greeting(name, message="Good morning!"):
        print("Hello", name + ', ' + message)

>>> greeting('Caleb')
Hello Caleb, Good morning!
>>> greeting('Sydney', "How are you?")
Hello Sydney, How are you?
4. Object-Oriented Programming and Python | Next Section Previous Section

Cisco Press Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Cisco Press and its family of brands. I can unsubscribe at any time.