How to End a Function Def in Python?


Problem Formulation

Given a function definition in Python, starting with the keyword def:

def f(x, y):
    p = x * y
    return p

res = f(2, 3)
print(res)
# 6

How to know when a “def” of a function ends? For example, in Java and C++, functions are enclosed with opening and closing parentheses {...}, so the ending of a function is not ambiguous.

Ending a Function Syntactically

In Python, whitespace carries meaning with regards to the indentation level of expressions. The inner function body is indented compared to the environment it is defined in, per default by four empty spaces. Once the indentation level falls back to the level the function is defined, the function syntactically ends. Formally, a block ends when it encounters a non-empty line indented at most at the same level with the function definition. This non empty line is not part of that block.

Have a look at this example where we define three lines apart from the function definition—the first two lines are part of the function body, the third is not.

def f():
    x = 1 # first line
    x = 2 # second line
x = 3 # third line, not part of f()

So, if you run this code snippet, you’ll obtain the following result — only the third line is executed as it’s not part of the not-executed function:

def f():
    x = 1 # first line
    x = 2 # second line
x = 3 # third line, not part of f()
print(x)
# 3

Theoretically, you can also write a one-liner function body right after the colon like so:

def f(): pass

If you need to run multiple expressions in a one-line function definition, you can do so with the semicolon. However, this is not recommended because it hurts readability:

def f(): pass; pass

Ending a Function Semantically

Todo

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



Source link

Latest articles

Related articles

Leave a reply

Please enter your comment!
Please enter your name here