[Tutor] The Boolean operator "and"

Glen Wheeler gew75 at hotmail.com
Fri Aug 6 11:10:58 CEST 2004

> I have a question about one sentence in the fine Python book I'm
> presently studying, Practical Python, by Magnus Lie Hetland (Apress). The
> sentence is "Actually, if x is false, it returns x--otherwise it returns
> y." This sentence is in the paragraph on p. 109 that begins,
> 'The Boolean operators have one interesting property: They only evaluate
> what they need to. For instance, the expression  x and y  requires both x
> and y to be true; so if x is false, the expression returns false
> immediately, without worrying about y. Actually, if x is false, it
> returns x--otherwise it returns y. (Can you see how this give the
> expected meaning?) This behavior is called short-circuit logic: the
> Boolean operators are often called logical operators, and as you can see,
> the second value is sometimes "short-circuited." This works with or, too.
> In the expression x or y, if x is true, it is returned, otherwise y is
> returned. (Can you see how this makes sense?)'
> In the sentence I'm questioning, "Actually, if x is false, it returns
> x--otherwise it returns y", it seems to me that if x evaluates to False,
> False is returned, not x itself, (which might be "3 > 4").
> Am I confused? Or quibbling?

  I'd say a little bit of both ;).

  Mr Hetland is (of course) correct in his statement you quote above.  The
key part is where he states ``if x is false''.  This is not ``x evaluates to

  A quick interpreter session to hopefully clarify what he is trying to say:

>>> x = 3 < 4
>>> x
>>> x is True
# Note how x actually *is* True
>>> x is False

  The point is that any logical expression is not stored as a string, but as
either True or False.  This is neat, since it implies that the expected
value of any logical expression will be True or False.  Thus, we have if
  Any logical statement or expression is evaluated before assignment to the
variable holding that statement actually occurs.

>>> x = 1 > 0
>>> y = 1 < 0
>>> x and y
>>> x or y
>>> x is False
>>> x is True

  I hope this helps clear things up.


More information about the Tutor mailing list