Why can there be only one "return" in this function?


#1

There can only be one "return" in this function. Why can I not place a return under cost -= 50 and one return under cost -=20?

Thanks! Appreciate it :smile:


#2

It's possible to put return statement in the branches of the if statement without changing the behaviour of the function, but there is no need to. Note that the return statement in your function is not inside the if or elif part and thus will be executed independent of the number of days.

With return statements inside of the if and elif parts the function would look like this:

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

If you rent the car for less than 3 days it still costs money and the function still needs to return a value, so we now added 2 return statements, but could not even leave out the original return statement.
I think the function from your post is easier to read and the better option, although it's possible to write a function with multiple return statements that does the same job.


#3

Thanks for responding :smile:
But isn't it illegal to place those returns within each if/elif branch? I tried that and it wouldn't pass me.


#4

I tested it with the code from my post and it lets me pass.

Can you copy the code that doesn't work and include the error message you get?


#5

Mhhmmmm...
It says the following are wrong (on different comment boxes since because I'm a new user I can't post more than one photo per comment):


#6

and this one:


#7

and also this one:


#8

In your first and second picture you don't seem to return anything when both days >= 7 and day >= 3 are False.

In the second and third picture you use return cost -= 20. That's equivalent to cost = cost - 20, but in Python you can't use assignments as values, instead use return cost - 20.