Functions#
This notebook is based on materials kindly provided by the IN1900 team.
We have seen how we can use loops to avoid repeating code. This helps us obey the DRY principle. (Question: what is the DRY principle?) Functions are another way to reuse code.
A function is a short block of code/program statements. These statements are executed when we call the function. This way, we can perform a common operation many times without having to rewrite the code each time.
We define a new function with the statement def
. def
is followed by the function name, and a set of parentheses. If the function has parameters, we list those inside the parentheses. The function body follows on the next lines, and must be indented.
The function ends when there are more no more indented lines, or by the return
statement.
# This line does not belong to the function
def function_name(parameter):
# This line is part of the function (has indent)
# ...
return output_value
# This line does not belong to the function (no indent)
Defining functions#
Let’s define a function for calculating the mean value of two numbers:
def mean(a, b):
result = (a + b) / 2
print(result)
Function Calls#
Using a function is also known as calling a function. We have called several functions, for example print()
.
We can call our mean
function:
mean(5, 10)
7.5
Exercise: Make a Function #
Define a greeting function. It should take a name as input, and print a greeting. Then use the function to greet first Alice, and then Bob. The output should be:
Hello Alice
Hello Bob
def greet(name):
#Your solution here
greet('Alice')
greet('Bob')
Cell In[4], line 4
greet('Alice')
^
IndentationError: expected an indented block after function definition on line 1
Returning Values#
Our mean
function only prints the result without storing it.
If we want to use the result in our program, we must store it.
We can do this by passing the results back to where the function was called, with the return
statement.
def mean(a, b):
result = (a + b) / 2
return result
We can store the return value like below. (Is this a good variable name? Why/why not?)
output = mean(5,4)
print(returned_value)
return
ends the function#
When we have calculated a result, we can send it to the caller with return
.
When Python executes the return
-statement, the function is terminated immediately.
In the example below, the line below the return
-statement will never be executed.
def mean(a, b):
result = (a + b) / 2
return result
print(result)
output = mean(5,4)
Exercise: Returning Values #
Define a function, get_last(sequence)
, that returns the last element of a list.
Then use the function on the list below:
#Your solution
# and then print out the last item in items
items = ["first", "second", "third"]
print(get_last(items))
Parameters#
Most functions need some information to work with. We can pass information to functions as parameters.
We define the parameter names in the def
-statement. Inside the function, we can use these parameter names. When the function finishes, these parameters/local variables are removed.
def subtract(a, b):
return a - b
print(subtract(10, 5))
Notice that the variable names in the function call are not the same as the variable names in the function definition. What counts is the order of the parameters.
spam = 10
eggs = 5
print(subtract(spam, eggs))
a = 10
b = 5
print(subtract(b, a))
Parameters with Default Values#
If a parameter often has a certain value, we can set that value as the default.
For instance, we can write a function to issue a fine. Most fines are for NOK 750, so we set that as the default amount:
def issue_fine(amount = 750):
#here we need to do something
print("Fine sent for NOK", amount)
Case Law Exercise: Functions to get Information #
Here, we will continue working with our JSON data. Define a function that takes a case as an argument, and returns the name of the court.
The code below applies this function to the cases in a loop. Make sure you use the function name that is called in the loop. We use a slightly different URL this time, to make sure we get three different courts.
You might need to browse the data.
import requests
import json
def #your code here
URL = "https://api.case.law/v1/cases/?full_case=true&decision_date_min=2011-01-01&page_size=3"
data = requests.get(URL).json()
cases = data["results"]
for case in cases:
print(get_court_name(case))
Library Data Exercise: Function to get the Title #
Here, we will continue working with our JSON data. Define a function that takes a book as an argument and returns the book title.
The code below applies this function to the books in a loop. Make sure you use the function name that is called in the loop.
You might need to browse the data.
import requests
import json
def #your code here
URL = "https://api.nb.no/catalog/v1/items?digitalAccessibleOnly=true&size=3&filter=mediatype:bøker&q=Bing,Jon"
data = requests.get(URL).json()
embedded = data['_embedded']
items = embedded['items']
for item in items:
print(get_title(item))
Key Points#
We should make functions to avoid repeating ourselves
Functions help us make modular programs
Functions have parameters
Use the
return
-statement for sending information back to the caller