Transportation


#1



Transportation
Error: -It looks like rental_car_cost returns 120 instead of the correct amount (100) for 3 days.

Can any1 tell me what is wrong with my code?


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


#2

you don't update your care_rent variable. take a look:

test = 20
test - 10
print test
print test -10
test = test - 10
print test

you really need to updated (re-assign) your variable, otherwise it won't persist


#3

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

The above is my initial code which works well. However when it is not as elegent when compared to the example:

def finish_game(score):
    tickets = 10 * score
    if score >= 10:
        tickets += 50
    elif score >= 7:
        tickets += 20
    return tickets

When I try to imitate the example:

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

it failed horribly.

Seems like in the example, the function works even tho the variables are used multiple time. However it doesn't work in my imitation. Care to explain why?


#4

You forgot about =. Check example code, there's a = after +. You aren't saving your new value.

tickets += 50

can be replaced with

tickets = tickets + 50

So you must use

car_rent -= 50

instead of

car_rent - 50

to save new value to car_rent variable


#5

That explains. Some1 mislead me and telling it those 2 are essentially the same.

Thanks! =)


#6

which i was trying to show you in my example:

test = 20
test - 10
print test
print test -10
test = test - 10
print test

but you seemed to have missed it


#7

a = a + b

Is actually not always the same as

a += b

+= is in-place add, sometimes that's not possible, like for integers, since they can't be changed.
If += is not defined for that value, then the two are equivalent, but they can be defined as different operations.

a = []
b = a
a += [1]
print b  # [1]

a = []
b = a
a = a + [1]
print b  # []

Defining them goes like:

class MyClass(object):
    def __add__(self, other):
        print 'used +'

    def __iadd__(self, other):
        print 'used +='


a = MyClass()
a + 1  # used +

a = MyClass()
a += 1 # used +=

If __iadd__ is commented out above, then both will use __add__ (+)

Documentation for __iadd__:
https://docs.python.org/2/reference/datamodel.html#object.__iadd__