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
A return statement effectively ends a function; that is, when the Python interpreter executes a function's instructions and reaches the return , it will exit the function at that point.
start() returns an integer that is the position in the text where the match starts, while end() returns the ending position. There's no tuple involved in the code you show.
To end a program in Python, use the sys. exit() function. Python sys module contains a built-in function called sys. exit() to exit the program.
All functions must be defined before any are used. However, the functions can be defined in any order, as long as all are defined before any executable code uses a function.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With