# [Tutor] defining functions.. why return?

Andrei Kulakov ak@silmarill.org
Thu, 06 Dec 2001 02:28:50 -0500

```On Wed, Dec 05, 2001 at 11:09:58PM -0800, Frank Holmes wrote:
>   I am working my way thru "SAMS teach yourself Python in 24 hrs by Van
> Laningham (funny, it seems to be taking me a lot more than 24 hrs...) and I
> have a question  concerning defining functions.
>   In his example (chapter 7 "functions and modules) Mr. Van Lanningham
> shows the following example for defining a function:
>
> 1.  def julian_leap (y):
> 2.  if (y%4)==0:
> 3.     return 1
> 4.  return 0
>
>   Concerning the "return" statements, he says the interpreter keeps track
> of the place where the function was called and the return statement just
> means "goto the place in the code that you started from".

Well, let's say you have this code:

def julian_leap(y):
[...]
return

print "blah"
julian_leap(year)
print "dragh"

What happens here is that first it prints 'blah', then it runs the
function, then it reaches 'return' inside function, and then it returns
to the same place between the two print statements, and then it goes to
the next line and print 'dragh'.

>   I don't understand... The example gives 2 "return" statements... where
> are they "goto  ing"?

When you have two returns, only one of them will run, the first one..:

def func():
return 1
return 2

It will always return 1, and never 2, because as soon as it reaches
first 'return', the function "returns", to pun, to wherever it started
from. Normally, if you have 2 returns, at least the first of them is in
some sort of conditional, because if it wasn't, it would make the rest
of the function pointless (it'd never run).

>   I used the example function in a form:
>
> for x in years: [1900, 1040, 1968, 1955]
>    if julian_leap (x):
>          print"1"
>    else:
>          print "2"
>
>   it seemed to work regardless of whether I used both returns, or either,
> or none at all. So why the "return 1 and return 0 statements?

THe thing is, if a function doesn't execute a return statement, it
returns 0 when it finishes.

def func():
if 0: return 1  # never runs

This function will return 0. In the book you're reading, the function
returns 0 explicitly for clarity. If you drop it, it'll make no
difference.
>
>                                             thanx
>
> _________________________________________________________________