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:
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)!
-
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, andbase. Thebaseparameter has a default value ofhttps://sandboxdnac2.cisco.com. This means that if thebaseparameter is not provided when calling the function, it will default tohttps://sandboxdnac2.cisco.com. -
A function returns a value using the
returnkeyword. In this case, the function returns a dictionary with the keyx-auth-tokenand 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.
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.