[Tutor] Logical Operators
Barry.Carroll at psc.com
Thu Apr 6 18:44:26 CEST 2006
There are two topics to understand here:
1. what "TRUE" and "FALSE" mean in Python, and
2. how Python evaluates "X and Y".
The tutorial "Instant Python" by Magnus Lie Hetland has good, short
descriptions of these two topics, so I'll borrow from it. You can find
the document at:
1. "All values in Python can be used as logic values. Some of the
"empty" ones, like , 0, "" and None represent logical falsity,
while most other values (like , 1 or "Hello, world")
In your examples, 5 and 1 are both considered 'TRUE', while 0, of
course, is considered "FALSE".
2. "Now, logical expressions like a and b are evaluated like this:
First, check if a is true. If it is not, then simply return it.
it is, then simply return b (which will represent the truth
of the expression.) The corresponding logic for a or b is: If a
true, then return it. If it isn't, then return b."
Python evaluates your example expressions like this:
a. Get the first sub-expression. x
Get the value of x. 5
Is 5 a "TRUE" value? Yes
Since the operator is "and", get the
second sub-expression. 1
Is 1 a "TRUE" value? Yes
Return it. 1
b. Get the first sub-expression. y
Get the value of y. 0
Is 0 a "TRUE" value? No
Since the operator is "and",
STOP and return the sub-expression. 0
Does this help? Try this: change the 'and' operator in your examples to
'or'. What would the return value be now?
5 or 1 = ???
0 or 1 = ???
barry.carroll at psc.com
We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed
> -----Original Message-----
> Date: Thu, 6 Apr 2006 16:06:11 +0530
> From: "Kaushal Shriyan" <kaushalshriyan at gmail.com>
> Subject: [Tutor] Logical Operators
> To: tutor at python.org
> <6b16fb4c0604060336p74dbe676jb88838d0d9aa5b23 at mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
> I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap04.htm
> about Logical operators
> I didnot understood
> >>> x = 5
> >>> x and 1
> >>> y = 0
> >>> y and 1
> How 5 and 1 means 1 and 0 and 1 means 0
More information about the Tutor