Does a return statement always have to be the last line of a function?


In Python, if there is a return statement within a function, does the return always have to be the last line of code in the function?


That does not always have to be the case, but usually, a return statement is the last line of code in a function since it should be run last.

The reason for this is because of how a return statement works. When a return statement is run inside of a function, the function will immediately terminate and return that value, and none of the remaining code lines in the function will run. Because of this, functions usually have the return statement at the very end, so that all the other lines of code in the function will complete first before the function terminates and returns a value.


# This function will return 20
def example():
  total = 20
  return total
  # These lines will not run
  # because they follow a return.
  total += 10
  return total

9 posts were split to a new topic: How does Return work?

3 posts were split to a new topic: How can I create a function utilizing datetime?

so the β€œprint(example())” function will output β€œ20” ?

Correct. The print() function first calls the function, example() which returns 20. That value is then handed to the print() function as its argument.

1 Like