How does Python know where the end of a function is?
indentation, python, syntax
Solution
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
Problem
I'm just learning python and confused when a "def" of a function ends? I see code samples like: ``` def myfunc(a=4,b=6): sum = a + b return sum myfunc() ``` I know it doesn't end because of the return (because I've seen if statements... if FOO than return BAR, else return FOOBAR). How does Python know this isn't a recursive function that calls itself? When the function runs does it just keep going through the program until it finds a return? That'd lead to some interesting errors. Thanks