1

I am trying to recreate a problem from our classwork:

Write a program that can handle a shopping event. First, it requests the number of items bought, then asks for each items' price and tax rate. Then prints the total cost.

Example:
How many items you bought: 2

For item 1
Enter the price: 10
Enter the tax rate: 0

For item 2
Enter the price: 20
Enter the tax rate: 8
Your total price is 31.6


I have no knowledge on how I would compute for items larger than 1. ie my code works for 1 item.

items = int(input("How many items did you buy? "))

for i in range(1, items+1, 1):
    print("For item ",i)
    price = float(input("Enter the price: "))
    tax_rate = float(input("Enter the tax rate: "))
    total = price + price*(tax_rate/100)

print("Your total price is", total)

I need to somehow save the totals after each iteration and add them all up. I am stumped.

Note: This is an introduction to python course and also my first programming course. We've only learned for loops thus far.

2
  • Use a list and .append() an item at every loop. Commented Feb 20, 2018 at 3:26
  • Thanks @iBug. I saw this when I was trying to use google at first and even tried to use it myself, but unfortunately we have not learned how to append yet. Commented Feb 20, 2018 at 3:48

1 Answer 1

1

You need to have an initialized counter to have a running total.

items = int(input("How many items did you buy? "))
total = 0

for i in range(1, items+1, 1):
    print("For item ",i)
    price = float(input("Enter the price: "))
    tax_rate = float(input("Enter the tax rate: "))
    total += price + price*(tax_rate/100)

print("Your total price is", total)
Sign up to request clarification or add additional context in comments.

2 Comments

That's really neat. I'm browsing google to learn more about the operator +=. Thank you!
@CharlesGrealy it's a great tip to learn. Instead of doing say i = i + 1, it's just i += 1. Essentially it is "take this variable and set it equal to itself plus whatever is on the right"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.