16 — Practice solutions

← Questions

These are independently written explanations, not an official marking scheme.

16A

Slices: "OMP", "ING", "CMUIG".

def count_vowels(text):
    count = 0
    for character in text.lower():  # One comparison rule handles either case.
        if character in "aeiou":
            count += 1
    return count

lower() supplies a new string for traversal; the original argument is unchanged.

16B

def write_totals(source_path, output_path):
    total = 0
    with open(source_path, "r", encoding="utf-8") as source:
        for line in source:
            if line.strip() != "":  # A blank line is not a numeric record.
                total += int(line)
    with open(output_path, "w", encoding="utf-8") as output:
        output.write(str(total) + "\n")  # write() does not add a newline itself.

An empty source produces 0 followed by a newline. Using append mode would retain old results, contrary to “replacing”.