[Tutor] 'return' statements
Daniel Yoo
dyoo@hkn.EECS.Berkeley.EDU
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
> function!!):
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():
... pass
...
>>> x = doNothing()
>>> print x
None
###
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
...
>>> square(5)
25
>>> square(square(5))
625
###
Also, 'return' does a quick exit out of the function.
###
>>> def testReturn():
... return "I've returned!"
... print "I'll never get here."
...
>>> x = testReturn()
>>> x
"I've returned!"
###
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
represent Truth.
###
>>> 'A' == 'A'
1
>>> 'A' == 'B'
0
###
So you can abuse the language by doing something like:
###
>>> ('A' == 'A') + ('A' == 'B')
1
###