Transportation notation question


#1

Hi there,

I have a question about the notation used in the transportation section of the "taking a vacation" lesson.

When using if/elif to add discount to car rental cost depending on the days, i would have assumed the code would look like this:

def rental_car_cost(days):
    carcost = days * 40
    if days >= 7:
        carcost - 50
    elif days >= 3:
        carcost - 20
    return carcost

However, this doesn't work. But when you copy the notation from the example and change the if/elif outcomes from "carcost - number" to "carcost -= number" it works:

def rental_car_cost(days):
    carcost = days * 40
    if days >= 7:
        carcost -= 50
    elif days >= 3:
        carcost -= 20
    return carcost

I would just like to know why my first code wouldn't work, and what " -= " or "+=" means.

Thanks for your help!


#2

The above is an expression, with no outcome.

The above is a statement, with the outcome assigned to the variable.


#3

Meaning of compound operators...

There are shorthands that is effectively used in programming

Like...

x = x + 3 can be written asx += 3
x = x - 3can be written asx -= 3
x = x * 3 can be written asx *= 3
x = x / 3can be written asx /= 3

Note : There is no space between operator(+,-,*,/) and =.

These shorthands are called compound assignment operators .

Now lets come to your code...

def rental_car_cost(days):
    carcost = days * 40
    if days >= 7:
        carcost - 50
    elif days >= 3:
        carcost - 20
    return carcost

You can see inside Your code, you're not updating your code but directly subtracting from it.
So when you return carcost its not get updated (re-assigned) thus the code does not work!


#4

Thanks for your speedy responses! I think I understand it now


#5

Compound operator is more descriptive. To augment means to increase. Only addition, multiplication and exponentiation (with non rational exponents) will increase the value.

Subtraction, division and rational exponents lead to a decrease in the value.


#6

Cheers!!! :slight_smile: keep up the good work!! :thumbsup:


#7

right thing! I'm going to update my post! :slight_smile:


#8

def rental_car_cost(days):
car = days * 40
if days >=7:
car -=50
elif days >=3 or days <=6:
car -=20
else:
return car

that code still not work for me, it says -->None instead of the correct amount (40) for 1 days.
can you give me some insight pls


#9

Here are a few things to try:
-remove the else statement
-remove the "or days..."
-try changing "car" to "rental_car_cost" (no " " )

Hope this helps.


#10

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