Notebook 0: Python warm-up#

Use these short exercises to practise basic Python patterns before the data notebooks. Replace ... where shown, run the check, and change one example to see what happens.

Hide code cell source

from pathlib import Path
import sys

# Find the repository from the notebook folder, solutions folder, or project root.
for _candidate in (Path.cwd().resolve(), *Path.cwd().resolve().parents):
    if (_candidate / "notebooks" / "workshop_checks.py").is_file():
        PROJECT_ROOT = _candidate
        break
else:
    raise FileNotFoundError(
        "Open this notebook inside the cloned workshop repository; "
        "notebooks/workshop_checks.py is required."
    )

sys.path.insert(0, str(PROJECT_ROOT / "notebooks"))

from workshop_checks import Check, run_checks

check = Check()

1: Predict the output#

What will this print? Choose A, B, or C before running the check.

numbers = [1, 2]
alias = numbers
alias.append(3)
len(numbers)
  • A: 2

  • B: 3

  • C: an error

answer_1 = ""  # replace with A, B, or C
Hint

Assignment gives two names to the same list. Appending through either name changes that list.

Hide code cell source

run_checks("00_python_warmup_predict", locals())

2: Use variables and arithmetic#

Calculate the total cost for six items at seven units each.

price = 7
quantity = 6
total = ...
Hint

Multiply price by quantity.

Hide code cell source

run_checks("00_python_warmup_arithmetic", locals())

3: Clean a string#

Remove surrounding whitespace and make the word lowercase.

word = "  PYTHON  "
clean_word = ...
Hint

Use the string methods .strip() and .lower().

Hide code cell source

run_checks("00_python_warmup_string", locals())

4: Write a small function#

Complete is_even. It should return True for even numbers and False for odd numbers.

def is_even(number):
    ...
Hint

The remainder operator is %. An even number has remainder zero after division by two.

Hide code cell source

run_checks("00_python_warmup_function", locals())

5: Build a list with a comprehension#

Create the squares of the numbers 1 through 4.

squares = [number ** 2 for number in ...]
Hint

Use range(1, 5).

Hide code cell source

run_checks("00_python_warmup_list", locals())

6: Read a dictionary#

Select the value stored under the course key.

person = {"name": "Ada", "course": "Python"}
course = ...
Hint

Use square brackets with the key name.

Hide code cell source

run_checks("00_python_warmup_dictionary", locals())