Transportation: How do I do the else statment?


Hello everyone:slight_smile:,
I don't know how to code the else statement.
I would be very greatful if someone can help me.
If you can, could you please also check for bugs and errors and explain ( I don't understand why if I am given a chunk of code that is very similar but different:worried:)

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



I see your thought process about this if/elif/else block. Typically, there are three parts to a block like this:

  1. The if statement
  2. The elif statement(s)
  3. The else statement

Although this is the typical format, the else statement is not always necessary. Specifically in this case, the else statement is purposely left off because there are only two conditions to test for.

Secondly, the reason we use an if/elif block instead of an if/else block is because we need only one or none of these conditions to evaluate. The elif statement gives us this functionality.

So to recap, the rental_car_cost() function only needs an if and an elif block to function correctly. If you get rid of else: on line 24, you should be good to go!

Hope this helps your understanding :slight_smile:


Thank you : - ) :relaxed:


I'm not sure why rental_car_cost returns None.:confused:


return days*40
You need an else statement specifying what the program should do when days are less than three. Add this to end of your program and you'll be good to go


The answer above works just fine, and is the correct answer for how you structured your code.

I apologize about being ambiguous with omitting the else statement; the reason I told you this is because of the way I structured my code:

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

If you look at my if and elif statements, you'll notice that they do not return anything; they just modify cost. At the end of the function definition, cost is returned regardless.

So, if neither of the if or elif statements are entered, cost's default value is returned, which is days * 40.

You can simply write return cost outside of your if and elif statements, or you can put it inside an else statement, as suggested above.


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