1

I am writing a code to practice. I am learning lists in python, and I decided to use it through grocery buying. Basically I will input the numbers in the list by calling the function in console, and those numbers will add up and the tax of the total after adding them, and the output should be the total.

The problem is there is something wrong in my math or somewhere where the output is coming incorrect.

def taxes(num):
  if num >= 0 and num <10:
    num = (num + num*0.07)
    return num
  elif num >=10 and num <=19:
    num = (num + num*0.10)
    return num
  elif num >=20:
    num = (num + num*0.15)
    return num

def list_grocery(lst):
  #new_list = []
  total = 0
  for ele in range(0, len(lst)):
    total = taxes(total + lst[ele])
  return total

For example

when I call list_grocery([1,2,3,4,4,7])

the total should be 24.15 while my function gives out 28.0336190345.

Can someone please help and see where in my math I am doing something wrong. Thank You in advance.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101

5 Answers5

2

You are computing taxes on the each previous total (thus computing taxes on taxes), as opposed to summing the taxes computed on each item.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
1

Inside the loop, you're applying taxes to the subtotal, which is compounding the tax.

total = taxes(total + lst[ele])

Call the taxes function just on the price of each item instead.

total = total + taxes(lst[ele])

Also, instead of looping over a range and indexing the list, you can loop over the elements of the list directly.

for elem in lst:
    total = total + taxes(elem)
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
1

You could try using +=, that adds and assigns to the original variable, so change this line:

total = taxes(total + lst[ele])

To:

total += taxes(lst[ele])

Your code always brings total into the taxes function as well, you shouldn't. Like in my code it doesn't.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

You’re apply tax to already taxed items. First item in your list goes through is 1. It is taxes to be 1.07. Then the number is added to you’re next number 2. Which is sent to the taxes function and come back as 3.07 + 3.07x.07. You have basically compounded you tax.

You should change the line

Total = taxes(total + lst[ele])

Try

Total += taxes(lst[ele])

0
    def list_grocery(lst):
  #new_list = []
  total = 0
  new_total = 0
  for ele in range(0, len(lst)):
    total = total +  lst[ele]
    **new_total = taxes(total)**
  return new_total

I simply added the new variable of new_total, which I used for taxing the total after it was compounded. This way it avoids mixing the taxes part.