Exercise 09-17:

Change Program 9.6 to display the phonebook size in the main menu. Consider the number of names it contains as its size.

Answer:

##############################################################################
# Python From Scratch
# Author: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2025 - LogiKraft 2025
# Site: https://pythonfromscratch.com
# ISBN: 978-85-7522-949-1 (Paperback), 978-85-7522-950-7 (hardcover), 978-85-7522-951-4 (ebook)
#
# File: chapter 09/exercise-09-17.py.py
##############################################################################
address_book = []


def ask_name():
    return input("Name: ")


def ask_phone():
    return input("Phone: ")


def show_data(name, phone):
    print(f"Name: {name} Phone: {phone}")


def ask_filename():
    return input("File name: ")


def search(name):
    mname = name.lower()
    for p, e in enumerate(address_book):
        if e[0].lower() == mname:
            return p
    return None


def new():
    global address_book
    name = ask_name()
    phone = ask_phone()
    address_book.append([name, phone])


def delete():
    global address_book
    name = ask_name()
    p = search(name)
    if p is not None:
        del address_book[p]
    else:
        print("Name not found.")


def modify():
    p = search(ask_name())
    if p is not None:
        name = address_book[p][0]
        phone = address_book[p][1]
        print("Found:")
        show_data(name, phone)
        name = ask_name()
        phone = ask_phone()
        address_book[p] = [name, phone]
    else:
        print("Name not found.")


def list_all():
    print("\nAddress Book\n\n------")
    for e in address_book:
        show_data(e[0], e[1])
    print("------\n")


def read():
    global address_book
    filename = ask_filename()
    file = open(filename, "r", encoding="utf-8")
    address_book = []
    for l in file.readlines():
        name, phone = l.strip().split("#")
        address_book.append([name, phone])
    file.close()


def save():
    filename = ask_filename()
    file = open(filename, "w", encoding="utf-8")
    for e in address_book:
        file.write(f"{e[0]}#{e[1]}\n")
    file.close()


def validate_integer_range(question, start, end):
    while True:
        try:
            value = int(input(question))
            if start <= value <= end:
                return value
        except ValueError:
            print(f"Invalid value, please enter a number between {start} and {end}")


def menu():
    print(
        """
   1 - New
   2 - Modify
   3 - Delete
   4 - List
   5 - Save
   6 - Read

   0 - Exit
"""
    )
    print(f"\nNames in address book: {len(address_book)}\n")
    return validate_integer_range("Choose an option: ", 0, 6)


while True:
    option = menu()
    if option == 0:
        break
    elif option == 1:
        new()
    elif option == 2:
        modify()
    elif option == 3:
        delete()
    elif option == 4:
        list_all()
    elif option == 5:
        save()
    elif option == 6:
        read()
Click here to download the file