Decisions#

This notebook is based on materials kindly provided by the IN1900 team.

How can we use Python to automatically recognize different features in our data, and take a different action for each? Here, we will learn how to write code that executes only when certain conditions are true.

We can tell Python to take an action depending on the value of a variable:

length = 42
if length > 100:
    print('greater')

We can also include an alternate path, else:

length = 42
if length > 100:
    print('greater')
else:
    print('smaller')
print('done')
smaller
done

This code can be illustrated with a flowchart: if illustration

elif#

We can chain multiple if-tests with elif, short for “else if”.

length = 42
if length > 100:
    print('greater')
elif length < 0:
    print('Oops, negative length?')
else:
    print('smaller')
print('done')
smaller
done

Exercise: multiple hits #

With elif, only the first test that yields True is executed.

The code below is supposed to show a warning for temperatures above 70, but there is a bug. Find two different ways to fix the code, so that the warning is displayed.

temperature = 120

if temperature > 0:
    print("it's warm")
elif temperature <= 0:
    print("it's freezing")
elif temperature > 70:
    print("WARNING: dangerously hot")
it's warm

boolean Expressions#

The comparisons that are part of the if statements in the examples are Boolean expressions. Boolean expressions include comparisons (>, <), equality (==) and inequality (!=). Boolean expressions evaluate to True or False.

boolean Connectors#

We can use the boolean connectors or operators to build larger expressions. The boolean connectors in Python are and, or and not.

warm = True
cloudy = False

print(warm and cloudy)
print(warm or cloudy)
if warm and not cloudy:
    print("Remember sunscreen!")
False
True
Remember sunscreen!

Exercise: Boolean Operators #

Again we look at the temperature test. This time, use a Boolean operator to fix this test so that the warning is displayed.

temperature = 120

if temperature > 0:
    print("it's warm")
elif temperature <= 0:
    print("it's freezing")
elif temperature > 70:
    print("WARNING: dangerously hot")
it's warm

Case Law Exercise: count dissenting opinions #

In the code below, we loop through a list of cases from the Case Law Api, then loop through the opinions for each of those cases. Each opinion has a "type" field which describes if it’s a majority opinion, dissenting opinion or concurring opinion. First, try to run the code below to check if you can print out the value of this field for each opinion:

import requests
import json

URL = "https://api.case.law/v1/cases/?jurisdiction=ill&full_case=true&decision_date_min=2011-01-01&page_size=20"
data = requests.get(URL).json()

cases = data["results"]
for case in cases:
    opinions = case["casebody"]["data"]["opinions"]
    for opinion in opinions:
        print(opinion["type"])
---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
File /opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/requests/models.py:974, in Response.json(self, **kwargs)
    973 try:
--> 974     return complexjson.loads(self.text, **kwargs)
    975 except JSONDecodeError as e:
    976     # Catch JSON-related errors and raise as requests.JSONDecodeError
    977     # This aliases json.JSONDecodeError and simplejson.JSONDecodeError

File /opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/json/__init__.py:346, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    343 if (cls is None and object_hook is None and
    344         parse_int is None and parse_float is None and
    345         parse_constant is None and object_pairs_hook is None and not kw):
--> 346     return _default_decoder.decode(s)
    347 if cls is None:

File /opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/json/decoder.py:337, in JSONDecoder.decode(self, s, _w)
    333 """Return the Python representation of ``s`` (a ``str`` instance
    334 containing a JSON document).
    335 
    336 """
--> 337 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    338 end = _w(s, end).end()

File /opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/json/decoder.py:355, in JSONDecoder.raw_decode(self, s, idx)
    354 except StopIteration as err:
--> 355     raise JSONDecodeError("Expecting value", s, err.value) from None
    356 return obj, end

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

JSONDecodeError                           Traceback (most recent call last)
Cell In[7], line 5
      2 import json
      4 URL = "https://api.case.law/v1/cases/?jurisdiction=ill&full_case=true&decision_date_min=2011-01-01&page_size=20"
----> 5 data = requests.get(URL).json()
      7 cases = data["results"]
      8 for case in cases:

File /opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/requests/models.py:978, in Response.json(self, **kwargs)
    974     return complexjson.loads(self.text, **kwargs)
    975 except JSONDecodeError as e:
    976     # Catch JSON-related errors and raise as requests.JSONDecodeError
    977     # This aliases json.JSONDecodeError and simplejson.JSONDecodeError
--> 978     raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Now, try to modify the code below to count the number of dissenting opinions by using an if test with opinion["type"]. If you find a dissent, you will need to increase the variable dissent_count:

import requests
import json

URL = "https://api.case.law/v1/cases/?jurisdiction=ill&full_case=true&decision_date_min=2011-01-01&page_size=20"
data = requests.get(URL).json()

dissent_count = 0

cases = data["results"]
for case in cases:
    opinions = case["casebody"]["data"]["opinions"]
    for opinion in opinions:
        'Your code here'

print("Number of dissents:", dissent_count)

Library Data Exercise: Count Fulltext Documents #

In the code below, we loop through a list of items from the National Library API. Each item has a dictionary accessInfo, containing a key isDigital. The corresponding value is a Boolean which is True if the document is available digitally in fulltext. First, try to run the code below to check if you can print out the value of isDigital for each item:

import requests
import json

URL = "https://api.nb.no/catalog/v1/items?size=20&filter=mediatype:b%C3%B8ker&q=Bing,Jon"
data = requests.get(URL).json()
embedded = data['_embedded']
items = embedded['items']

for item in items:
    accessInfo = item['accessInfo']
    isDigital = accessInfo['isDigital']
    print(isDigital)

Now, try to modify the code below to count the number of digital fulltext documents by using an if test with isDigital. If you find a digital document, you will need to increase the variable fulltext_count:

import requests
import json

URL = "https://api.nb.no/catalog/v1/items?size=20&filter=mediatype:b%C3%B8ker&q=Bing,Jon"
data = requests.get(URL).json()
embedded = data['_embedded']
items = embedded['items']

fulltext_count = 0

for item in items:
    accessInfo = item['accessInfo']
    isDigital = accessInfo['isDigital']
    # your code here

Key Points#

  • We use if-statements to control program flow

  • if-statements can have an else-part

  • We can chain multiple if-statements with elif

  • if-statements use Boolean expressions, which can be True or False