Search code examples
pythoncalculation

How is it possible to add condition to this code that if the employee is below the age of 30, he only has to pay half of his taxable income?


income_input = {"Gerard": 120000, "Tom": 60000, "Roos": 40000}

def calculate_tax(income_input):
    for item in income_input:
        income = income_input[item]
        # print(income)

        if (income <= 50000):
            tax = (0.3*income)

        elif (income > 50000) and (income <= 100000):
            tax = (0.4 * income)

        elif (income > 100000):
            tax = (0.5*income)  
        else:
            pass
        income_input[item] = int(tax)
    return income_input

print(calculate_tax(income_input))

Output: {'Gerard': 60000, 'Tom': 24000, 'Roos': 12000}

So I can get a simple calculator using dictionaries. However, how can I add 'age' condition to that? As I understand the age should be added first to dictionary something like this:

income_input  = {'Gerard': 
            {'age': 50, 'salary': 120000},
            'Tom':
         {'age': 28,'salary': 60000},
          'Roos':
         { 'age': 25,'salary': 40000}
} 

Then I have to make a condition for calculation that if the 'age' <= 30 then the employee has to pay only half of his taxable income?

So TOM and ROOS have to pay 12.000 and 6.000 accordingly.

Please could anybody help with that?

Thanks!


Solution

  • You can use income_input.items() to have an access to the dict in income_input which contains both the income and the age (see info dict below). Then, you can access them by their keys.

    income_input = {
        'Gerard': {'age': 50, 'salary': 120000},
        'Tom': {'age': 28,'salary': 60000},
        'Roos': { 'age': 25,'salary': 40000}
    }
    
    def calculate_tax(income_input):
        tax_dict = {}
        for name, info in income_input.items():
            income = info['salary']
            age = info['age']
            tax = 0.0
            if income <= 50000:
                tax = 0.3 * income
            elif income > 50000 and income <= 100000:
                tax = 0.4 * income
            elif income > 100000:
                tax = 0.5 * income
    
            # check for age
            if age <= 30:
                tax = tax/2.0
    
            tax_dict[name] = int(tax)
    
        return tax_dict
    
    tax_dict = calculate_tax(income_input)
    print(tax_dict)