• JUPYTER
  • FAQ
  • View as Code
  • Python 3 (ipykernel) Kernel
  • View on GitHub
  • Execute on Binder
  • Download Notebook
  1. learn-python3
  2. notebooks
  3. beginner
  4. exercises
In [ ]:
# EXECUTE THIS ONE FIRST!

from pathlib import Path

# Constants for the exercises:
WORKING_DIR = Path.cwd()
DATA_DIR = WORKING_DIR.parent / "data"

1. Sum numbers listed in a file¶

Fill ____ pieces of the code below. sum_numbers_in_file function takes a input file path as argument, reads the numbers listed in the input file and returns the sum of those numbers. You can assume that each line contains exactly one numeric value.

In [ ]:
def sum_numbers_in_file(input_file):
    total = 0
    with ____(input_file) as ____:
        for line in ____:
            ____ = line.strip()  # Remove potential white space
            total += float(____)
    return _____
In [ ]:
in_file = DATA_DIR / "numbers.txt"
assert sum_numbers_in_file(in_file) == 189.5

2. Reading first word from each line of a file¶

Implement find_first_words function which takes an input file path as argument. The function should find the first word of each line in the file and return these words as a list. If a line is empty, the returned list should contain an empty string for that line.

In [ ]:
# Your implementation here
In [ ]:
in_file1 = DATA_DIR / "simple_file.txt"
in_file2 = DATA_DIR / "simple_file_with_empty_lines.txt"

expected_file_1 = ["First", "Second", "Third", "And"]
assert find_first_words(in_file1) == expected_file_1

expected_file_2 = ["The", "", "First", "nonsense", "", "Then"]
assert find_first_words(in_file2) == expected_file_2

This website does not host notebooks, it only renders notebooks available on other websites.

Delivered by Fastly, Rendered by OVHcloud

nbviewer GitHub repository.

nbviewer version: 8b013f7

nbconvert version: 7.2.3

Rendered (Tue, 10 Jun 2025 07:09:25 UTC)