Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python def function: How do you specify the end of the function?

Tags:

python

syntax

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

like image 906
Dan Avatar asked Oct 15 '09 16:10

Dan


People also ask

How do you define the end of a function in Python?

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.

How do you start and end a function in Python?

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.

How do you end a function in Python 3?

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.

Can you define a function after you call it Python?

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.


1 Answers

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 
like image 170
Stephan202 Avatar answered Sep 23 '22 03:09

Stephan202