[Tutor] defining functions.. why return?

alan.gauld@bt.com alan.gauld@bt.com
Thu, 6 Dec 2001 14:31:43 -0000

> shows the following example for defining a function:
> 1.  def julian_leap (y):
> 2.  if (y%4)==0:
> 3.     return 1
> 4.  return 0

First lines 2-4 should be indented 

def julian_leap (y):
  if (y%4)==0:
     return 1
  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".

Thats correct although in this case it also substitutes 
the returned value for the function, thus:

test = julian_leap(1999)
print test

jumping into the function and the "return 0" line has the 
effect of returning to the first line with the function 
call replaced by the retuned value(0) so test gets set
to 0. Then when we print test we get 0 out.

>    I don't understand... The example gives 2 "return" 
> statements... 

But only 1 will ever be executed. If the first one(inside the if statement)
gets executred the program will never reach the second one. If the 'if' test
fails the program drops through to the second return statement.

Thus the function either returns 1(which python considers 'true') 
or 0(which python thinks means 'false).

> are they "goto  ing"?

Back to the line that the function was called from.
test = julian_leap(1999) 
in the case above.

> for x in years: [1900, 1040, 1968, 1955]

This is wrong syntax, the colon must come at the end 
and you don't need the 'years' bit, see below

>     if julian_leap (x):
>           print"1"
>     else:
>           print "2"

Try changing it to:

for x in [1900, 1040, 1968, 1955]:
     print julian_leap (x)

You should get a set of 1 or 0 results printed

Alan G.