[Tutor] tutorial 5.1.3

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri May 23 00:26:43 2003


On Thu, 22 May 2003, David Scott wrote:

> In the Python Tutorial (the one that comes with Python), in section
> 5.1.3, there is something that I do not understand:
>
> >>>def f(x): return x % 2 != 0 and x % 3 != 0
> ...
> >>>filter(f, range(2, 25))
> [5, 7, 11, 13, 17, 19, 23]
>
> That example is used to compute primes.


Hi David,


(Just wanted to point out that f() doesn't detect primes by itself: f(25)
will return True since it's neither divisible by two or three... but 25 is
still not prime.)



> From what I understand, the "return" statement is returning the tested
> value (passed in from the range) if it passes both tests.

It might help if we parenthesize everything there, so that the result of
the return statement is clearer, if a little more cluttered:


###
def f(x):
   return ((x % 2 != 0) and (x % 3 != 0))
###



The return statement,

    return [expr]


returns the value of that [expr] part, and not necessarily the parameter
'x'.  In the statement above,


   return ((x % 2 != 0) and (x % 3 != 0))


we'd say that


     ((x % 2 != 0) and (x % 3 != 0))


is the "subexpression" part of that statement, and the result of the
subexpression is what is given back to the caller.


(Once we have more confidence that we understand how Python is grouping
things, we'd go without the parentheses:


     x % 2 != 0 and x % 3 != 0
)




> However, it seems to me that the return statement would return either a
> 1 or a 0 and nothing else, because of the "and".

Yes, exactly.  But it's not just because of the 'and' part.  If we had
left it as:


###
def f(x):
   return (x % 2 != 0)
###


then the value that's being returned is still the one that's the result of
the expression:

    (x % 2 != 0)

and not just the 'x' part.



It might help if the expression was one where 'x' wasn't visually the
first part of the return value, like:


###
def double_of_x(x):
    return 2 * x
###



> return (test expression) and (test expression). If both are true, then
> the "and" is true. else, the entire statement is false.
>
> What am I missing or misunderstanding here?


You got the right idea.  Try doing some more functions interactively, and
the idea of what 'return' does should solidify.

By the way exploring functions with filter() adds slightly more
complexity, so I'd recommend playing around with filter() after you get
function return values down.



Good luck to you!