How to improve the for-loop, function and conditional statement?

So I wrote two different codes, the first one to calculate the amount of income tax with a flat rate system. The second one with two tax brackets. The problem with the first code is that I want to add the names of the people in the result but I don't know how to.

In the second code I wanted two let the first 50k fell within the first tax bracket, the if statement, and the resting amount in the second, the else statement. but python only looks if the amount is higher than 50k.

Can someone please describe what to do?

first

income_data = [{'name': 'Gerard', 'income': 140000},{'name': 'Mark','income':60000},{'name': 'Sanne', 'income':40000}]

# for d in income_data: I think these two lines are unnecessary
  # print(d['income'])

def tax_rate(d):
  tax_rate = d * 0.31
  return (tax_rate)

lst = list()
for d in income_data:
  tax = tax_rate(d['income'])
  lst.append(tax)

print(lst)

second

income_data = [{'name': 'Gerard', 'income': 140000},{'name': 'Mark','income':60000},{'name': 'Sanne', 'income':40000}]

# for d in income_data:
 # print (d['income'])

def tax_rate(d):
  if d < 50001:
    tax_rate = 0.25 * d
  else:
     tax_rate = 0.35 * d

     return(tax_rate)

lst = list()
for d in income_data:
  tax = tax_rate(d['income'])
  lst.append(tax)

print(lst)

1 answer

  • answered 2021-10-12 16:32 gimix

    Both in the first and the second code snippets you may add the tax_rate to the dictionary entries. Replace

    lst.append(tax)
    

    with

    d['tax-rate'] = tax
    

    In the second snippet when the income is greater than 50k you just apply the highest rate. You should still apply the lower rate to the first 50k instead:

    if d < 50001:
        tax_rate = d * 0.25
    else:
        highest = d - 50000
        tax_rate = 50000 * 0.25 + highest * 0.35
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum