Transportation


#1

I’ve a question regarding the usage of ( -= ) here. Why should we place an ( = ) sign after the ( - ) sign? Shouldn’t just placing a ( - ) be enough?
The question was to subtract 50 from the cost if the days were 7 or greater, and 20 if it was 3 or greater.

def rental_car_cost(days):
cost = 40 * days

if days >= 7:
  cost -= 50  
elif days >= 3:
  cost -= 20
return cost

#2

-= is a shorthand, this:

cost -= 20

is a shorthand for:

cost = cost - 20

so the variable is updated, only using - isn’t enough, then the variable is not updated, there is just a temporary subtraction, which i always like to demonstrate the following way:

x = 10
print x # 10
print x -5 # 5
print x # 10
x = x - 5
print x # 5

#4

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