Transportation (Indentation)


I was just curious how you are able to just type return cost without having to indent yourself because it seems when I indent myself there is an indentation error.

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

The code above works, but I had to write a return cost after cost -= 20 then re-type return cost


Hey @rami62392

I’m not sure what the problem you’re having is, as the code you’ve posted runs fine for me. If I copy your code exactly, then at the end add a print statement to check the output from rental_car_cost, I don’t get an error.

To answer your question, though.

When you’re defining a function in Python, everything after the def line should be indented including the return statement .

This is because all the code that you want to be included in your function is “nested” inside the function. For Python to know that it’s part of the function, it needs to be indented. (There are no curly braces { } in Python.)

For a basic function definition, the last thing you’d want the function to do is return some output, so the return statement is the last line of indented code inside the function. Like this:

def example_function(number):
  # take a number and calculate the square
  num_squared = number ** 2
  # return the number
  return num_squared

# carry on the rest of the program here.

In the code you’ve posted, the indent on the return is right. If you indented again, Python would treat the return as part of the elif branch of your code. :slight_smile:


Got it! Thank you so much!


No worries. :slight_smile:

If there’s anything else you get stuck with, just pop on to the forums and someone will give you a hand. :slight_smile:


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