Writing Your Own Functions · practice
Refactor the Menu Actions
Before rebuilding the interactive menu, you will extract two of its actions with fixed data. No input() yet. That lets you focus on
Displaying the items
The Chapter 7 list branch had two paths:
if len(items) == 0:
print("The list is empty.")
else:
number = 1
for item in items:
print(f"{number}. {item}")
number += 1
Move that work into a function:
def show_items(items):
if len(items) == 0:
print("The list is empty.")
else:
number = 1
for item in items:
print(f"{number}. {item}")
number += 1
The
show_items(books)
Inside the function, the items refers to that list. The function does not care whether the caller named it books, tasks, or places.
Returning the count message
You will give the count action a slightly different boundary:
def count_message(items):
return f"Items stored: {len(items)}"
This function builds and returns text. The caller prints it:
print(count_message(books))
Why use two styles in one lesson?
Because functions are defined by their jobs, not by a rule that every function must print or every function must return. show_items is a display operation that may print several lines. count_message builds one reusable
The list stays with the caller
The functions do not create the collection:
books = []
show_items(books)
books.append("Kindred")
books.append("A Wizard of Earthsea")
show_items(books)
print(count_message(books))
The caller owns the sequence of events. The functions handle individual operations.
Expected output:
The list is empty.
1. Kindred
2. A Wizard of Earthsea
Items stored: 2
This is a small version of the final refactor. The top-level code says what happens. Each function explains how one action works.
Why does show_items receive the list as a parameter?
Task
Complete both menu-action
show_items(items) must:
print
The list is empty.if thehas no items; otherwise print every item on a numbered line starting at
1.
count_message(items) must return:
Items stored: 2
with the actual length in place of 2.
Keep the given calls. Expected output:
The list is empty.
1. Kindred
2. A Wizard of Earthsea
Items stored: 2