Basics III 6. Exercises
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.
- Add at least two names and phone numbers.
- Print one phone number using its key.
- Update one phone number.
- Delete one entry.
- 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
functo every item inlst - 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.