Can someone explain the reason for this difference


#1

meal = 44.50
tax = 0.0675
tip = 0.15

meal = meal + meal * tax
total=meal+meal*tip

print("%.2f" % total)
total_1 = meal + meal*(tip+tax)
print ("%.2f" %total_1)

Corresponding output
54.63
57.84
None


#2

What difference? Be more specific.


#3

That is a very good question. At first sight, I got a little problem with that too. But the key is to realize that you assigned meal to meal + meal*tax. Thus, meal will be not just 44.50 anymore. It will be modified for the rest of the code. Look at the image how I proved that. Did I answer your question? Just let me know, greetings from Brazil!


#4

There is nothing wrong with,

total = meal + meal * tax
total += meal * tip

We cannot add the tip to the tax since the tip is calculated on the meal before the tax is added, and we don't want to pay tax on the tip, either.

Consider also, order of operations, and the distributive property:

y = x * t + x * p + x
y = x * (t + p + 1)

For

x = 10
t = 0.0675
p = 0.15

we get,

y = 10 * (0.0675 + 0.15 + 1)
y = 10 * 1.2175
y = 12.18