Back to Module 4

Exercises

These exercises use the ideas from this module in a more guided way.

Exercise 1. Build a phonebook dictionary

Create a dictionary named phonebook.

  1. Add at least two names and phone numbers.
  2. Print one phone number using its key.
  3. Update one phone number.
  4. Delete one entry.
  5. Print the final dictionary.

Starter code:

phonebook = {
    "Amy": "111-2222",
    "Ben": "333-4444"
}

print(phonebook["Amy"])

phonebook["Ben"] = "999-0000"
del phonebook["Amy"]

print(phonebook)

Exercise 2. Swap two values with tuple unpacking

Start with:

a = 5
b = 10

Swap the values in one line and print them.

Starter code:

a = 5
b = 10

a, b = b, a
print(a)
print(b)

Exercise 3. Write a function that applies and adds

Write a function apply_and_sum(func, lst).

The function should:

  • apply func to every item in lst
  • add all the results together
  • return the final sum

Starter code:

def apply_and_sum(func, lst):
    total = 0
    for item in lst:
        total += func(item)
    return total

print(apply_and_sum(lambda x: x * 2, [1, 2, 3]))

Expected result:

12

Exercise 4. Count the number of lines in a file

Create a small text file first, then read it and count the lines.

Example file contents:

apple
banana
cherry

Starter code:

count = 0

with open("fruits.txt", "r", encoding="utf-8") as f:
    for line in f:
        count += 1

print(count)

Question:

  • What happens if you add one more line to the file?

Extra challenge

Write a new function count_long_words(words, min_length) that returns how many words are at least min_length characters long.

Back to Module 4