Skip to content

Functions

In Python, a function is a block of code that only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.

You have already familiarized yourself with indented code block in Python during the loops and conditional statements. Functions are similar to loops and conditional statements in that they are also indented code blocks.

Defining a Function

You can define a function by using the def keyword, followed by the function name and parentheses (). The code block within every function starts with a colon : and is indented.

Consider the following example:

function example
import requests

def get_token(user, pw, base="https://sandboxdnac2.cisco.com"): # (1)!
    """return cc token"""

    auth = (user, pw)
    url = base + "/dna/system/api/v1/auth/token"
    rs = requests.post(url, auth=auth, verify=False)
    token = rs.json()["Token"]

    return {"x-auth-token": token} # (2)!
  1. This is the function definition, also referred to as the signature of the function. The function name is get_token, and it takes three parameters: user, pw, and base. The base parameter has a default value of https://sandboxdnac2.cisco.com. This means that if the base parameter is not provided when calling the function, it will default to https://sandboxdnac2.cisco.com.

  2. A function returns a value using the return keyword. In this case, the function returns a dictionary with the key x-auth-token and the value of the token.

The indented block is called the body of the function. The body of the function is executed when the function is called.

calling the function
token = get_token("devnetuser", "Cisco123!")
print(token)
Output
{'x-auth-token': 'eyJ0eXAiOi.....'}

Parameters are usually useful, but you can declare a function without any parameters. This is useful if you need to call it many times. For example: This function asks the user for confirmation and exits if the answer is not yes or y. It also doesn't have a return statement. This means that the function will return None by default.

function without parameters and return statement
def confirm():
    answer = input("Are you sure? ")
    if answer.lower() in ("y", "yes"):
        print("Great!")
    else:
        exit()