Why Doesn't This Work When I Do It By Hand


#1

I understand the correct code for this exercise is:

meal = 44.50
tax = 6.75 / 100
tip = 15.0 / 100

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

print("%.2f" % total)

My issue is that when I do it by hand, it seems totally off.

If I sub in the new value of “meal” as meal = meal + meal * tax in the total line, you get:

total = (meal + meal * tax) + (meal + meal * tax) * tip

With the order of operations and with the initial values, you get:

44.50 + 44.50 * .0675 + 44.50 + 44.50 * .15 =
44.50 + 3.00375 + 44.50 + 6.675 =
98.67875

Which is pretty clearly not correct. Maybe the code in line 10 takes the above math and does something to it that yields the correct answer of 54.63? I’m trying to understand the syntax here more than specifically how to pass this exercise. Thanks!


#2
x = meal + meal * tax
y = x + x * tip

Remember that the value is being overwritten in the first step when assigning back on to itself.

y = x + x * tip
  = x * (1 + tip)

but x = meal + meal * tax

  = meal + meal * tax * (1 + tip)
  = meal * (1 + tax) * (1 + tip)

#3
>>> tab = 44.50
>>> tax = 6.75 / 100
>>> tip = 15.0 / 100
>>> print (round(tab * (1 + tax) * (1 + tip), 2))
54.63
>>> print (round(tab * (1 + tax + tip + tax * tip), 2))
54.63
>>> 

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.