#1

# Assign the variable total on line 8!

meal = 44.50
tax = 0.0675
tip = 0.15

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

print("%.2f" % total)

DOnt understand why meal = 44.50 and 44.50+44.50* 0.067
and why did total chose second meal variable and not the first?

#2

Total chose the second meal variable because it is the latest one. As soon as you asign meal+meal*tax to meal, the original value for meal is overwritten.
If you want to keep the original variable, give a different name for one of the meal variables.

#3

Variables in python can change throughout your code - so once you assign it a value, that doesn't mean it will keep that value throughout your code. You could for example just change the value of a variable in your code e.g.

bill = 0.2
print(bill)
bill = 'fish'
print(bill)

After the 1st line of code bill equals fish after the 3rd line of code it now equals fish.

However this probably isn't an example you'll see in practice a lot. What is more common is that you see variables that are additive. So in the example you posted meal starts off with 1 value then has something added to it. Another thing that can be tricky to get your head around is that meal appears on both sides of the equation e.g.

meal = meal + meal * tax

This is ok. Think of it as taking the original variable value, doing something with it and then assigning it to the original variable name. It's worth understanding this as it is a very common way of changing variables.

#4

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