[Tutor] 'return' statements
Mon, 14 Aug 2000 17:53:12 -0700 (PDT)
On Sun, 13 Aug 2000, Albert Antiquera wrote:
> I've finished the calculator program I was making thanks to the help
> of Daniel Yoo. One statement that continue to elude me to fully
> understand it is the 'return' statement. On some text they said
> 'return' is a "go back to the start of the function" another said that
> it is a "terminator" of a function. Can somebody explain it and please
> provide some examples like when to use ' 0 ' and ' 1 ' after a return
> statement and also this usage (Thanks, Daniel for this very useful
No problem. About 'return': All functions will give back a value to the
"calling" function. Even when you don't say anything like "return",
functions will at least send back the "None" object. Take a look:
>>> def doNothing():
>>> x = doNothing()
>>> print x
What a 'return' statement allows you to do is specify what sort of value
you want your functions to give back. For example:
>>> def square(x): return x * x
Also, 'return' does a quick exit out of the function.
>>> def testReturn():
... return "I've returned!"
... print "I'll never get here."
>>> x = testReturn()
What I was doing in:
> def readNum():
> x = raw_input("Enter a value for X:")
> y = raw_input("Enter a value for Y:")
> return (float (x),float(y)) <<<<<<<<<<<<what exactly is return doing here?????
was returning a list of values (technically a tuple). You might not have
been introducted to lists yet; wait till you get there, and you'll
understand what's happening.
> another example:
> def julian_leap(y =2000):
> if (y%4) == 0:
> return 1 <<<< I guess this says "true" but I'm not really sure
> return 0 <<< what is this returning????
It's literally either returning the number 1 or 0. There isn't a distinct
"true" or "false" data type; Python conveniently reuses 1 and 0 to
>>> 'A' == 'A'
>>> 'A' == 'B'
So you can abuse the language by doing something like:
>>> ('A' == 'A') + ('A' == 'B')