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


#1

Question

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?

Answer

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.

Example

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