레이블이 Python Tutorial인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Python Tutorial인 게시물을 표시합니다. 모든 게시물 표시

2025년 3월 19일 수요일

Python Address Book: Build a Simple Contact Manager (Code Included

address_book.py

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:

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:

  1. display_menu(): This function prints the menu options to the console, allowing the user to choose an action.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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:

  1. Save the Code: Copy the code above and save it as a .py file (e.g., address_book.py).
  2. Open Command Prompt: Press the Windows key, type "cmd," and press Enter to open the Command Prompt.
  3. 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.
  4. 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!






Python Calculator GUI - Build a Simple Calculator with Tkinter (approx. 60 characters) Search Description:

 




import tkinter as tk

def button_click(number):
    """Handles button clicks for numbers and the decimal point."""
    current = entry.get()
    entry.delete(0, tk.END)
    entry.insert(0, str(current) + str(number))

def button_clear():
    """Clears the entry field."""
    entry.delete(0, tk.END)

def button_equal():
    """Evaluates the expression in the entry field."""
    try:
        expression = entry.get()
        result = eval(expression)  # Be cautious with eval() - see notes below
        entry.delete(0, tk.END)
        entry.insert(0, str(result))
    except Exception as e:
        entry.delete(0, tk.END)
        entry.insert(0, "Error")

# --- Main Window Setup ---
window = tk.Tk()
window.title("Simple Calculator")
window.geometry("300x400")  # Set window size

# --- Entry Field ---
entry = tk.Entry(window, width=20, borderwidth=5, font=('Arial', 16))
entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10)

# --- Buttons ---
button_1 = tk.Button(window, text="1", padx=20, pady=10, command=lambda: button_click(1))
button_2 = tk.Button(window, text="2", padx=20, pady=10, command=lambda: button_click(2))
button_3 = tk.Button(window, text="3", padx=20, pady=10, command=lambda: button_click(3))
button_4 = tk.Button(window, text="4", padx=20, pady=10, command=lambda: button_click(4))
button_5 = tk.Button(window, text="5", padx=20, pady=10, command=lambda: button_click(5))
button_6 = tk.Button(window, text="6", padx=20, pady=10, command=lambda: button_click(6))
button_7 = tk.Button(window, text="7", padx=20, pady=10, command=lambda: button_click(7))
button_8 = tk.Button(window, text="8", padx=20, pady=10, command=lambda: button_click(8))
button_9 = tk.Button(window, text="9", padx=20, pady=10, command=lambda: button_click(9))
button_0 = tk.Button(window, text="0", padx=20, pady=10, command=lambda: button_click(0))
button_decimal = tk.Button(window, text=".", padx=20, pady=10, command=lambda: button_click("."))
button_add = tk.Button(window, text="+", padx=20, pady=10, command=lambda: button_click("+"))
button_subtract = tk.Button(window, text="-", padx=20, pady=10, command=lambda: button_click("-"))
button_multiply = tk.Button(window, text="*", padx=20, pady=10, command=lambda: button_click("*"))
button_divide = tk.Button(window, text="/", padx=20, pady=10, command=lambda: button_click("/"))
button_equal = tk.Button(window, text="=", padx=20, pady=10, command=button_equal)
button_clear = tk.Button(window, text="Clear", padx=20, pady=10, command=button_clear)

# --- Button Grid Layout ---
button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)

button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)

button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)

button_0.grid(row=4, column=0)
button_decimal.grid(row=4, column=1)

button_add.grid(row=1, column=3)
button_subtract.grid(row=2, column=3)
button_multiply.grid(row=3, column=3)
button_divide.grid(row=4, column=3)

button_equal.grid(row=5, column=2, columnspan=2)
button_clear.grid(row=5, column=0, columnspan=2)

window.mainloop()

How to Run:

  1. Save the Code: Save the code as a .py file (e.g., calculator.py).

  2. Run: Use the same method as before (Command Prompt/PowerShell or IDLE).

Explanation:

  •  Import: Imports the necessary GUI library.

  • Functions:

    • button_click(number): Appends the clicked number to the entry field.

    • button_clear(): Clears the entry field.

    • button_equal(): Evaluates the expression in the entry field using eval(). Important Note about 

  • GUI Elements: Creates the window, entry field, and buttons.

  • Button Commands: Each button's command is set to a function that handles the button click. lambda is used to pass the button's value to the button_click function.

  • Grid Layout: The grid() method is used to arrange the buttons in a grid layout.

  • : Starts the Tkinter event loop.

Important Security Note about 

The eval() function is powerful but can be dangerous if used with untrusted input. It executes arbitrary Python code. In this simple calculator, it's relatively safe because the user is expected to enter mathematical expressions. However, in a more complex application, you should never use eval() with input from an external source. Consider using a safer alternative like ast.literal_eval() or a dedicated expression parsing library.


Recommended Posts

Resolving: "error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools"" in AUTOMATIC1111

  Resolving: "error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools"" in AUTOM...