Home > OS >  Trying to find the tax for 2 items in a list
Trying to find the tax for 2 items in a list

Time:11-21

So I'm trying to write a calculator in python to get the total price of an infinite amount of items after-tax however I'm not sure how to do this.

    while True:
        after_tax = 0
        before_tax = []
        before_tax.append(int(input("How much is the item: ")))
    
        more = input("Anymore items? (y/n): ")
        if more.lower() == "n":
            after_tax = (before_tax[0] - (before_tax[0] * 0.1)   (before_tax[0] * 0.0845))
            print(after_tax)
            break
        else:
            for i in before_tax:
                after_tax  = i

result:

How much is the item: 10
Anymore items? (y/n): y
How much is the item: 10
Anymore items? (y/n): n
9.845

CodePudding user response:

It's not necessary to keep a list of the items; just sum the before-tax costs as they're entered and then multiply by the appropriate rate at the end.

before_tax = 0
while True:
    before_tax  = int(input("How much is the item: "))
    more = input("Anymore items? (y/n): ")
    if more.lower() == "n":
        break

tax_rate = 1.0845  # 8.45% sales tax
print(f"Before tax: {before_tax}")
print(f"After tax: {before_tax * tax_rate}")
How much is the item: 10
Anymore items? (y/n): y
How much is the item: 10
Anymore items? (y/n): n
Before tax: 20
After tax: 21.69

If you did have a list of numbers (maybe if there's something else you need to get out of the individual prices, like average, minimum/maximum, etc, such that only having the sum wouldn't do), the way to get the sum of the list is to use the builtin sum function:

before_tax = []
while True:
    before_tax.append(int(input("How much is the item: ")))
    more = input("Anymore items? (y/n): ")
    if more.lower() == "n":
        break

tax_rate = 1.0845  # 8.45% sales tax
print(f"Before tax: {sum(before_tax)}")
print(f"After tax: {sum(before_tax) * tax_rate}")

CodePudding user response:

I would do like that:

more = ''
after_tax = 0
before_tax = []
while more.lower() != "quit":
   more = input("Please add item, type 'quit' for quit: ")
   if more.isdigit():
       before_tax.append(int(more))
print(f'Before tax: {sum(before_tax)}, after tax: {sum(before_tax) * 1.0845:.2f}')

output

Please add item, type 'quit' for quit: 1
Please add item, type 'quit' for quit: 2
Please add item, type 'quit' for quit: 3
Please add item, type 'quit' for quit: 4
Please add item, type 'quit' for quit: quit
Before tax: 10, after tax: 10.85
  • Related