In Python whitespace is significant. The function ends when the indentation becomes smaller (less).
def f(): pass # first line pass # second line pass # <-- less indentation, not part of function f.
Note that one-line functions can be written without indentation, on one line:
def f(): pass
And, then there is the use of semi-colons, but this is not recommended:
def f(): pass; pass
The three forms above show how the end of a function is defined syntactically. As for the semantics, in Python there are three ways to exit a function:
- Using the
return
statement. This works the same as in any other imperative programming language you may know. - Using the
yield
statement. This means that the function is a generator. Explaining its semantics is beyond the scope of this answer. Have a look at Can somebody explain me the python yield statement? - By simply executing the last statement. If there are no more statements and the last statement is not a
return
statement, then the function exists as if the last statement werereturn None
. That is to say, without an explicitreturn
statement a function returnsNone
. This function returnsNone
:def f(): pass
And so does this one:def f(): 42