怎么可能给这个代码添加条件,如果雇员未满 30 岁,他只需支付其应税收入的一半?

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))

输出: {'Gerard':60000,'Tom':24000,'Roos':12000}

所以我可以用字典得到一个简单的计算器。但是,如何向其中添加 'age' 条件?据我了解,应该首先将年龄添加到字典中,如下所示:

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

那我要加个计算条件,如果'age' <= 30 那雇员就只交应税收入的一半?

所以 TOM 和 ROOS 必须相应地支付 12.000 和 6.000。

有人可以帮忙吗?

谢谢!

您可以使用 income_input.items() 访问 income_input 中的字典,其中包含收入和年龄(参见下面的 info 字典)。然后,您可以通过他们的密钥访问它们。

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)

使用上面指出的嵌套字典结构,您可以通过以下方式访问员工的年龄:

income_input['Gerard']['age']  # returns 50 

就我个人而言,使用每个员工只有两个字段的嵌套字典对我来说似乎有点矫枉过正。您可以考虑改用元组,并使用索引 0 访问年龄,使用索引 1 访问工资,例如:

income_input = {'Gerard': (50, 120000), 'Tom': (28, 60000), 'Roos': (25, 40000)}
income_input['Gerard'][0]  # returns 50
income_input = {"Gerard": (50, 120000), "Tom": (28, 60000), "Roos": (25,40000)}

for k in income_input:
    age, income = income_input[k]
    if (age <=30):
        if (income <= 50000):
            tax = (0.3*income)*0.5
        elif (income > 50000) and (income <= 100000):
            tax = (0.4*income)*0.5
        elif (income > 100000):
            tax = (0.5*income)*0.5 
        else:
            pass

我把年龄作为变量加入了字典