lundi 1 mars 2021

Instead of using primitive methods, should I be using a data structure?

This is my current code for a tax calculator based on age. I think that it would be easier to update in the future if I used data structures when calculating the brackets. Could someone help me make sense of this?

while True: #Loop the whole program
    from datetime import datetime, date #Get the Age of from user input
    
    print("Please enter your date of birth (dd mm yyyy)")
    date_of_birth = datetime.strptime(input("--->"), "%d %m %Y")
    
    def calculate_age(born):
        today = date.today()
        return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
    
    age = calculate_age(date_of_birth)
    
    print("You are " ,int(age), " years old.")
    
    #Get the Salary from user input
    def get_salary():
        while True:
            try:
                salary = int(input("Please enter your salary: "))
            except ValueError:
                print("You need to enter a number ")
            else:
                break
        return salary
    
    #Calculate the Amount that needs to be paid, using if,elif,else
    def contribution(age):
        if age <= 35:
            tax = (salary * 0.20)
        elif 36 <= age <= 50:
            tax = (salary * 0.20)
        elif 51 <= age <= 55:
            tax = (salary * 0.185)
        elif 56 <= age <= 60:
            tax = (salary * 0.13)
        elif 61 <= age <= 65:
            tax = (salary * 0.075)
        else:
            tax = (salary * 0.05)
    
        return tax
    
    #Print the amount 
    if __name__ == "__main__": # It's as if the interpreter inserts this at the top of your module when run as the main program.
        salary = get_salary() #get salary from get_salary()
        tax = contribution(age) #calculate the tax
        print("you have to pay", tax, " every month ")
    while True:
        answer = str(input("Do you need to do another calculation? (y/n): "))
        if answer in ("y", "n"):
            break
        print ("invalid input.")
    if answer == "y":
        continue
    else:
        print("Thank you for using this Calculator, Goodbye")
        break

So the code that I'm assuming that I need to change is:

#Calculate the Amount that needs to be paid, using if,elif,else
def contribution(age):
    if age <= 35:
        tax = (salary * 0.20)
    elif 36 <= age <= 50:
        tax = (salary * 0.20)
    elif 51 <= age <= 55:
        tax = (salary * 0.185)
    elif 56 <= age <= 60:
        tax = (salary * 0.13)
    elif 61 <= age <= 65:
        tax = (salary * 0.075)
    else:
        tax = (salary * 0.05)

    return tax

Also, I'm trying to learn so could you explain by putting #comments into the code :) Thank you!

Aucun commentaire:

Enregistrer un commentaire