Python program that creates a simple guest list management system. The program allows users to manage a guest list by adding guests, viewing the current list, and exiting the program through a simple and interactive interface.

Guest Class:
Represents a guest with attributes such as name, age, and favorite food.
Provides methods to convert a guest to a dictionary and create a guest from a dictionary.
User Input Functions:
getInt: Takes user input for an integer, handling exceptions.
getStr: Takes user input for a string, allowing only non-numeric characters.
File I/O Functions:
write_to_file: Writes a list of dictionaries to a JSON file.
read_from_file: Reads data from a JSON file, handling file not found and invalid JSON data errors.
update_file_with_new_data: Updates a JSON file with new data.
Guest Information Functions:
get_info: Takes user input for guest information (name, age, food) and validates the input.
add: Adds a specified number of guests to the guest list by taking user input.
view: Views the current guest list, printing the total number of guests and their information.
Menu Functions:
main_menu1: Provides a text-based menu for the user to choose between viewing the guest list, adding guests, or exiting the program.
main_menu2: Provides a numeric menu for the same options.
Execution:
The program starts by welcoming the user to the guest list.
The user is presented with a menu where they can choose to add guests, view the guest list, or exit the program.



import json

def getInt(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Error: Please enter a valid integer.")

def getStr(prompt):
    while True:
        user_input = input(prompt)
        if not any(char.isdigit() for char in user_input):
            return user_input
        print("Error: Numeric characters are not allowed.")

class Guest:
    def __init__(self, name, age, food):
        self.name = name.capitalize()
        self.age = age
        self.food = food

    def to_dict(self):
        return {"name": self.name, "age": self.age, "food": self.food}

    @classmethod
    def from_dict(cls, data):
        return cls(data["name"], data["age"], data["food"])

    def printInfo(self):
        print(f"Guest = {self.name} Age: {self.age} Favorite Food: {self.food}")

def get_info(y):
    if y == 1:
        y = f"{y}st"
    elif y == 2:
        y = "second"
    elif y == 3:
        y = f"{y}rd"
    else:
        y = f"{y}th"
    name = getStr(f"What is the {y} person's name? ")
    age = getInt(f"What is the {y} person's age? ")
    food = getStr(f"What is the {y} person's favorite food? ")
    return name, age, food

def write_to_file(data, filename="guest_list.json"):
    with open(filename, "w") as file:
        json.dump(data, file)

def read_from_file(filename="guest_list.json"):
    try:
        with open(filename, "r") as file:
            data = json.load(file)
            return data
    except FileNotFoundError:
        return []

def update_file_with_new_data(new_data, filename="guest_list.json"):
    existing_data = read_from_file(filename)
    updated_data = existing_data + new_data
    write_to_file(updated_data, filename)
def add(): # add to the json file
    guests = []
    y = getInt("How many guests do you want to add to the list? ")

    for _ in range(y):
        x = get_info(y)
        guests.append(Guest(*x).to_dict())

    # Update the file with new data
    update_file_with_new_data(guests)
def view(): # veiw the json

    # Read the updated list from the file
    read_guests = [Guest.from_dict(guestData) for guestData in read_from_file()]
    print(f"Total number of Guests: {len(read_guests)}")
    # Print the information
    for guest in read_guests:
        guest.printInfo()

def main_menu1():
    while True:
        option = getStr("Do you want to VIEW or ADD or EXIT the Guest List? ").upper()
        if option == "VIEW":
            view()
        elif option == "ADD":
            add()
        elif option == "EXIT":
            print("Exiting the program. Goodbye!")
            exit(99)
        else:
            print("Please type view or add")

def main_menu2():
    while True:
        print("\nMenu:")
        print("1. Add guests")
        print("2. View guest list")
        print("3. Exit")

        option = getInt("Enter your choice (1, 2, or 3): ")

        if option == 1:
            add()
        elif option == 2:
            view()
        elif option == 3:
            print("Exiting the program. Goodbye!")
            exit(99)
        else:
            print("Invalid choice. Please enter 1, 2, or 3.")

print("Welcome to The Guest List!")
main_menu2()

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *