Python Text-Based Address Book: A Beginner-Friendly Tutorial
This tutorial will guide you through creating a simple, text-based address book using Python. This project is perfect for beginners to learn fundamental programming concepts like dictionaries, loops, and user input. We'll break down the code step-by-step, explaining each part to ensure you understand how it works.
What is an Address Book?
An address book is a simple application that allows you to store and manage contact information, such as names and phone numbers. This version will be text-based, meaning it runs in the command prompt or terminal, and data is stored in memory while the program is running.
Prerequisites:
- Basic understanding of Python syntax.
- Python installed on your Windows machine. (You can download it from https://www.python.org/downloads/windows/)
Let's Get Started!
Here's the Python code for our address book:
import tkinter as tk
from tkinter import messagebox
def add_contact():
"""Adds a new contact to the address book."""
name = name_entry.get()
phone = phone_entry.get()
if name and phone:
address_book[name] = phone
update_listbox()
name_entry.delete(0, tk.END)
phone_entry.delete(0, tk.END)
else:
messagebox.showerror("Error", "Please enter both name and phone number.")
def view_contact():
"""Displays the selected contact's details."""
try:
selected_index = listbox.curselection()[0]
name = listbox.get(selected_index)
phone = address_book[name]
name_entry.delete(0, tk.END)
name_entry.insert(0, name)
phone_entry.delete(0, tk.END)
phone_entry.insert(0, phone)
except IndexError:
messagebox.showinfo("Info", "Please select a contact from the list.")
def search_contact():
"""Searches for a contact by name."""
search_name = search_entry.get()
if search_name in address_book:
messagebox.showinfo("Contact Found", f"Name: {search_name}, Phone: {address_book[search_name]}")
else:
messagebox.showinfo("Info", "Contact not found.")
def delete_contact():
"""Deletes a contact by name."""
try:
selected_index = listbox.curselection()[0]
name = listbox.get(selected_index)
del address_book[name]
update_listbox()
except IndexError:
messagebox.showinfo("Info", "Please select a contact to delete.")
def update_listbox():
"""Updates the listbox with the current contacts."""
listbox.delete(0, tk.END)
for name in address_book:
listbox.insert(tk.END, name)
# --- Main Window Setup ---
window = tk.Tk()
window.title("Address Book")
window.geometry("400x400")
# --- Address Book Data ---
address_book = {}
# --- Widgets ---
name_label = tk.Label(window, text="Name:")
name_label.grid(row=0, column=0, padx=5, pady=5)
name_entry = tk.Entry(window)
name_entry.grid(row=0, column=1, padx=5, pady=5)
phone_label = tk.Label(window, text="Phone:")
phone_label.grid(row=1, column=0, padx=5, pady=5)
phone_entry = tk.Entry(window)
phone_entry.grid(row=1, column=1, padx=5, pady=5)
add_button = tk.Button(window, text="Add Contact", command=add_contact)
add_button.grid(row=2, column=0, columnspan=2, padx=5, pady=5)
view_button = tk.Button(window, text="View Contact", command=view_contact)
view_button.grid(row=3, column=0, padx=5, pady=5)
search_label = tk.Label(window, text="Search:")
search_label.grid(row=4, column=0, padx=5, pady=5)
search_entry = tk.Entry(window)
search_entry.grid(row=4, column=1, padx=5, pady=5)
search_button = tk.Button(window, text="Search", command=search_contact)
search_button.grid(row=5, column=0, columnspan=2, padx=5, pady=5)
delete_button = tk.Button(window, text="Delete Contact", command=delete_contact)
delete_button.grid(row=6, column=0, columnspan=2, padx=5, pady=5)
listbox = tk.Listbox(window, width=40, height=10)
listbox.grid(row=7, column=0, columnspan=2, padx=5, pady=5)
# --- Start the GUI ---
window.mainloop()
Code Explanation:
- display_menu(): This function prints the menu options to the console, allowing the user to choose an action.
- add_contact(address_book):
- Takes the address_book dictionary as input.
- Prompts the user to enter the name and phone number of the new contact.
- Adds the contact to the address_book dictionary, using the name as the key and the phone number as the value.
- Prints a success message.
- view_contacts(address_book):
- Takes the address_book dictionary as input.
- Checks if the address book is empty. If it is, it prints a message indicating that.
- If the address book is not empty, it iterates through the dictionary and prints the name and phone number of each contact.
- search_contact(address_book):
- Takes the address_book dictionary as input.
- Prompts the user to enter the name of the contact to search for.
- Checks if the name exists as a key in the address_book dictionary.
- If the name is found, it prints the contact's name and phone number.
- If the name is not found, it prints a "Contact not found" message.
- delete_contact(address_book):
- Takes the address_book dictionary as input.
- Prompts the user to enter the name of the contact to delete.
- Checks if the name exists as a key in the address_book dictionary.
- If the name is found, it deletes the contact from the dictionary using the del keyword.
- If the name is not found, it prints a "Contact not found" message.
- main():
- This is the main function that runs the address book application.
- It initializes an empty dictionary called address_book to store the contacts.
- It enters a while True loop, which continues until the user chooses to exit.
- Inside the loop, it displays the menu, prompts the user for their choice, and calls the appropriate function based on their choice.
- If the user chooses to exit (option 5), the loop breaks, and the program ends.
- if __name__ == "__main__":: This ensures that the main() function is only called when the script is executed directly (not when it's imported as a module).
How to Run the Code on Windows:
- Save the Code: Copy the code above and save it as a .py file (e.g., address_book.py).
- Open Command Prompt: Press the Windows key, type "cmd," and press Enter to open the Command Prompt.
- Navigate to the Directory: Use the cd command to navigate to the directory where you saved the address_book.py file. For example, if you saved it in your Documents folder, you might type cd Documents and press Enter.
- Run the Script: Type python address_book.py and press Enter.
The address book menu will appear in the Command Prompt. Follow the instructions to add, view, search, and delete contacts.
Further Improvements:
- Data Persistence: Currently, the address book data is lost when you close the program. You can save the data to a file (e.g., a text file, CSV file, or JSON file) so that it persists between sessions.
- Error Handling: Add more robust error handling to handle invalid user input (e.g., non-numeric input when expecting a number).
- GUI Interface: Create a graphical user interface (GUI) using a library like Tkinter to make the address book more user-friendly.
- Sorting: Implement sorting functionality to display contacts in alphabetical order.
This tutorial provides a solid foundation for building more complex applications with Python. Experiment with the code, add new features, and have fun learning!
댓글 없음:
댓글 쓰기