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 were return None
. That is to say, without an explicit return
statement a function returns None
. This function returns None
:
def f():
pass
And so does this one:
def f():
42
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…