[Tutor] logic ?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu, 4 Oct 2001 14:34:05 -0700 (PDT)


On Thu, 4 Oct 2001, Jerry Lake wrote:

> for some reason, I can't get this to function
> properly, if someone can point me in the right
> direction, I'd appreciate it. the problem comes
> in at the if/else in the slope formula, it returns
> all slopes as 0.
> 
> def slope(x1, y1, x2, y2):
>    x = x1 - x2
>    y = y1 - y2
>    if (x or y == 0):
        ^^^^^^^^^^^^^

We as humans understand what you mean.  However, Python's seeing this in a
different light:

     if x or (y == 0):

That is, as long as x is a "true" value, the condition holds:

###
>>> 1 or 1 == 0
1
###


To fix this, you can write the logic like this:

###
if x == 0 or y == 0:
###


But I really like this way:

###
if 0 in (x, y):
###

which is neat since it reverses the "normal" role that we often see with
the 'in' operator.  Usually, we have the variable to the left of 'in', but
we don't have to be constrained to this.


Hope this helps!