Day 60 - OOP Data Management App - Editing Individual Records

Today, we will add a sub-menu to allow us to select an individual record and edit individual fields.

Starter Code

import pickle, os

class Employee:
    def __init__(self, strFN, strLN, intA, strE, flS):
        self.strFirstName = strFN
        self.strLastName = strLN
        self.intAge = intA
        self.strEmail = strE
        self.flSalary = flS

    def __str__(self):
        return f"{self.strLastName}, {self.strFirstName}".ljust(20)+f"{self.flSalary}".rjust(15)

    def getFirstName(self):
        return self.strFirstName

    def getLastName(self):
        return self.strLastName

    def getAge(self):
        return self.intAge

    def getEmail(self):
        return self.strEmail

    def getSalary(self):
        return self.flSalary

    def setAge(self, intA):
        if isinstance(intA, int) and intA >= 16:
            self.intAge = intA
        else:
            print("That's not a valid age.")

    def setSalary(self, flS):
        if isinstance(flS, float) and flS > 0:
            flSalary = flS
        else:
            print("That's not a valid salary.")



dEmp = {}

dStarter = {}

def saveData(dData):
    file = open("../oop_employee_data_pickle.txt", "wb")
    pickle.dump(dData, file)
    file.close()

def loadData(dData):
    if os.path.exists("../oop_employee_data_pickle.txt"):
        file = open("../oop_employee_data_pickle.txt", "rb")
        dLoaded = pickle.load(file)
        file.close()
    else:
        dLoaded = dData
        saveData(dData)

    return dLoaded

def showMenu():
    print("""
    1. Add an Employee
    2. Terminate an Employee
    3. Give Everyone a Raise
    8. List Employees
    9. Exit the Program
    """)

def getID(emp_data):
    if not emp_data:
        return "emp1"

    emp_numbers = [int(key[3:]) for key in emp_data.keys() if key.startswith("emp")]
    next_id = max(emp_numbers, default=0) + 1
    return f"emp{next_id}"

def addEmployee(emp_data):
    strFName = input("What is the first name? ")
    strLName = input("What is the last name? ")
    intAge = int(input("What is the age? "))
    strEmail = input("What is the email? ")
    flSalary = float(input("What is the salary? "))

    strID = getID(emp_data)

    emp_data[strID] = Employee(strFName, strLName, intAge, strEmail, flSalary)

    print(f"New Employee Added: {strFName} {strLName}, ID: {strID}")

    saveData(emp_data)

    return emp_data

def listEmp(emp_data):
    print("")
    for key in emp_data:
        print(f"ID: {key}".ljust(10), end="")
        print(emp_data[key])


def termEmp(emp_data):
    print("\nHere are the employees:")
    listEmp(emp_data)
    print("\nWho would you like to terminate?")
    strId = input("Enter the ID here: ")
    if (strId in emp_data):
        dEmpT = emp_data.pop(strId)
        print(f"{dEmpT['fname']} {dEmpT['lname']} was terminated.")
        saveData(emp_data)
        return emp_data
    else:
        print("This id doesn't exist.")

def giveAllRaise(emp_data):
    while True:
        strRaise = input("What is the raise percentage? (ex: 10): ")
        if (strRaise.isnumeric()):
            intRaise = int(strRaise)
            if (intRaise > 0 and intRaise <= 100):
                break
            else:
                print("You must enter a number between 1 and 100.")
        else:
            print("You must enter a number without decimals.")

    for key in emp_data:
        flSalary = emp_data[key]["salary"]
        flSalaryNew = flSalary * (1+(intRaise/100))
        print(f"{emp_data[key]['fname']} {emp_data[key]['lname']} got a raise from {flSalary:.2f} to {flSalaryNew:.2f}")
        emp_data[key]['salary'] = flSalaryNew

    saveData(emp_data)

    return emp_data


print("*"*60)
print("*"+"Employee Database".center(58)+"*")
print("*"*60)
print("")

dEmp = loadData(dStarter)

while True:
    showMenu()

    strMenu = input("What would you like to do? (Choose 1-9): ")

    if strMenu == "1":
        dEmp = addEmployee(dEmp)

    elif strMenu == "2":
        dEmp = termEmp(dEmp)

    elif strMenu == "3":
        dEmp = giveAllRaise(dEmp)

    elif strMenu == "8":
        listEmp(dEmp)

    elif strMenu == "9":
        break

    else:
        print("You need to enter a number for the menu choice.\n")


print("Thanks for using my program.")

Finished Code

import pickle, os

class Employee:
    def __init__(self, strFN, strLN, intA, strE, flS):
        self.strFirstName = strFN
        self.strLastName = strLN
        self.intAge = intA
        self.strEmail = strE
        self.flSalary = flS

    def __str__(self):
        return f"{self.strLastName}, {self.strFirstName}".ljust(20)+f"${self.flSalary:.2f}".rjust(15)

    def getFirstName(self):
        return self.strFirstName

    def getLastName(self):
        return self.strLastName

    def getAge(self):
        return self.intAge

    def getEmail(self):
        return self.strEmail

    def getSalary(self):
        return self.flSalary

    def setAge(self, intA):
        if isinstance(intA, int) and intA >= 16:
            self.intAge = intA
        else:
            print("That's not a valid age.")

    def setSalary(self, flS):
        if isinstance(flS, float) and flS > 0:
            self.flSalary = flS
        else:
            print("That's not a valid salary.")

dEmp = {}

dStarter = {}

def saveData(dData):
    file = open("../oop_employee_data_pickle.txt", "wb")
    pickle.dump(dData, file)
    file.close()

def loadData(dData):
    if os.path.exists("../oop_employee_data_pickle.txt"):
        file = open("../oop_employee_data_pickle.txt", "rb")
        dLoaded = pickle.load(file)
        file.close()
    else:
        dLoaded = dData
        saveData(dData)

    return dLoaded

def showMenu():
    print("""
    1. Add an Employee
    2. Terminate an Employee
    3. Give Everyone a Raise
    4. Employee Details
    8. List Employees
    9. Exit the Program
    """)

def getID(emp_data):
    if not emp_data:
        return "emp1"

    emp_numbers = [int(key[3:]) for key in emp_data.keys() if key.startswith("emp")]
    next_id = max(emp_numbers, default=0) + 1
    return f"emp{next_id}"

def addEmployee(emp_data):
    strFName = input("What is the first name? ")
    strLName = input("What is the last name? ")
    intAge = int(input("What is the age? "))
    strEmail = input("What is the email? ")
    flSalary = float(input("What is the salary? "))

    strID = getID(emp_data)

    emp_data[strID] = Employee(strFName, strLName, intAge, strEmail, flSalary)

    print(f"New Employee Added: {strFName} {strLName}, ID: {strID}")

    saveData(emp_data)

    return emp_data

def listEmp(emp_data):
    print("")
    for key in emp_data:
        print(f"ID: {key}".ljust(10), end="")
        print(emp_data[key])

def termEmp(emp_data):
    print("\nHere are the employees:")
    listEmp(emp_data)
    print("\nWho would you like to terminate?")
    strId = input("Enter the ID here: ")
    if (strId in emp_data):
        dEmpT = emp_data.pop(strId)
        print(f"{dEmpT['fname']} {dEmpT['lname']} was terminated.")
        saveData(emp_data)
        return emp_data
    else:
        print("This id doesn't exist.")

def giveAllRaise(emp_data):
    while True:
        strRaise = input("What is the raise percentage? (ex: 10): ")
        if (strRaise.isnumeric()):
            intRaise = int(strRaise)
            if (intRaise > 0 and intRaise <= 100):
                break
            else:
                print("You must enter a number between 1 and 100.")
        else:
            print("You must enter a number without decimals.")

    for key in emp_data:
        flSalary = emp_data[key]["salary"]
        flSalaryNew = flSalary * (1+(intRaise/100))
        print(f"{emp_data[key]['fname']} {emp_data[key]['lname']} got a raise from {flSalary:.2f} to {flSalaryNew:.2f}")
        emp_data[key]['salary'] = flSalaryNew

    saveData(emp_data)

    return emp_data

def employeeDetails(emp_data):
    listEmp(emp_data)
    print("Which Employee?")
    strId = input("Enter the ID from above: ")
    if strId in emp_data:
        curEmp = emp_data[strId]
        while True:
            print(f"""
                    Name: {curEmp.getFirstName()} {curEmp.getLastName()}
                    Email: {curEmp.getEmail()}
                    Age: {curEmp.getAge()}
                    Salary: ${curEmp.getSalary():.2f}
                    """)
            print("""
                    What would you like to do?
                    1. Edit Age
                    2. Edit Salary
                    3. Go to Main Menu 
                    """)
            strC2 = input("Enter Your Choice: ")
            if strC2 == "1":
                strAI = input("What is the new age?")
                if strAI.isnumeric():
                    intAI = int(strAI)
                    curEmp.setAge(intAI)
                    saveData(emp_data)
                else:
                    print("You must enter an integer.")

            elif strC2 == "2":
                strSI = input("What is the new Salary?")
                if strSI.replace(".", "").isnumeric():
                    flSI = float(strSI)
                    curEmp.setSalary(flSI)
                    saveData(emp_data)
                else:
                    print("You must enter a decimal number.")

            elif strC2 == "3":
                break
            else:
                print("That's not a valid choice.")

            return emp_data


print("*"*60)
print("*"+"Employee Database".center(58)+"*")
print("*"*60)
print("")

dEmp = loadData(dStarter)

while True:
    showMenu()

    strMenu = input("What would you like to do? (Choose 1-9): ")

    if strMenu == "1":
        dEmp = addEmployee(dEmp)

    elif strMenu == "2":
        dEmp = termEmp(dEmp)

    elif strMenu == "3":
        dEmp = giveAllRaise(dEmp)

    elif strMenu == "4":

        dEmp = employeeDetails(dEmp)

    elif strMenu == "8":
        listEmp(dEmp)

    elif strMenu == "9":
        break

    else:
        print("You need to enter a number for the menu choice.\n")


print("Thanks for using my program.")