0

I wrote a conditional statement in Python which increases a price depending on the corresponding state's tax rate at the time.

In the example below, I set the purchase_amount to $17 and the state to CA. The tax rate is 7.5%. Here's is how I formulated it to get the correct answer of $18.275.

state = "CA"
purchase_amount = 17

if state == "CA":
    tax_amount = .075

elif state == "MN":
    tax_amount = .095

elif state == "NY":
    tax_amount = .085

total_cost = tax_amount * purchase_amount + purchase_amount

However, I saw someone use a different formulation, as seen below, to get the same exact answer.

if state == "CA":
    tax_amount = .075
    total_cost = purchase_amount*(1+tax_amount)

I have never seen a percentage applied this way before.

My MAIN QUESTION is...Where did the integer 1 even come from??

My second question is... Why was it added to the tax_amount before multiplying it by the purchase_amount?

This was especially alarming because while it is nice to have concluded with the same correct answer regardless, I aspire to adequately read the coding styles of others.

Thank you so much for your help!

Robin
  • 3
  • 3
  • 2
    Do you remember the distributive property of multiplication over addition? `a*(b+c) = a*b+a*c`. Apply it here. – user2357112 May 20 '20 at 00:28
  • 2
    The `1` represents `100%`, so the total_cost equals `(100 percent + tax_amount percent) * purchase_amount`. – martineau May 20 '20 at 00:42

2 Answers2

3

Are you asking how to factor, like algebra 2 factoring. This would be called the distribution rule, the following lines are the same, by factoring out the common factor.

tax_amount * purchase_amount + purchase_amount

purchase_amount * ( tax_amount + 1 ) 
Bobby Ocean
  • 3,120
  • 1
  • 8
  • 15
  • Thanks so much for reminding me about the distributive property! Actually *naming* what was happening here helped me recall. – Robin May 21 '20 at 00:23
1

This is a math thing, if you want to add some % of the number to that number, you can do it two ways, your way:

(17 * .075) + 17 = 18.275

or their way:

17 * 1.075 = 18.275

these are both functionally the same calculation, just a different way of expressing it.