Calculate taxes with brackets
Here is how to calculate taxes using a bracket system. In many countries, taxes are defined by brackets, where a different tax rate applies to each bracket. We can define the brackets in Python as follows:
BRACKETS = [
(12000, 0.19),
(20000, 0.24),
(30000, 0.30),
(60000, 0.37),
(float('inf'), 0.45)]
This means that depending on the bracket, different tax rates will apply. For example:
- π For an income of 10,000, only 19% applies, resulting in a total tax of 1,900.
- π For an income of 15,000, 19% applies to 12,000 and 24% to 3,000, resulting in a total tax of 3,000.
- π For an income of 100,000, all brackets apply: 19% on 12,000, 24% on 8,000, 30% on 10,000, 37% on 30,000, and 45% on 40,000, resulting in a total tax of 36,300.
Now, let us define a function to calculate the tax:
def calculate_tax(income):
total_tax = 0
for i, (upper_limit, rate) in enumerate(BRACKETS):
lower_limit = BRACKETS[i - 1][0] if i > 0 else 0
taxable_income = min(income, upper_limit) - lower_limit
if taxable_income > 0:
total_tax += taxable_income * rate
if income <= upper_limit:
break
return total_tax
And we use it:
total_tax = calculate_tax(income=100000)
print(f"Tax is {total_tax:.2f}")
# Tax is 36300.00
βοΈ Exercises:
- Modify the
calculate_tax
function to return not only the tax in Euros to be paid but also the percentage of the salary.