[Tutor] or

John Fouhy john at fouhy.net
Fri Mar 30 04:54:54 CEST 2007


On 30/03/07, Christopher Spears <cspears2002 at yahoo.com> wrote:
> What I can't remember is what is 'or' in python.  For
> example, what if I want the loop to skip apples and
> pears?  I tried this:
>
> >>> for f in fruit:
> ...     if f != "apples" or "pears":
> ...             print f
> ...             print "This is not an apple or pear"
> ...
> apples
> This is not an apple or pear
> pears
> This is not an apple or pear
> oranges
> This is not an apple or pear
> >>>
>
> Actually maybe my problem is not asking the right
> question?  Should I be looking for 'and' instead of
> 'or' ?

Hi Christopher,

"or" is used to combine two boolean expressions.  What you wrote is
equivalent to:

for f in fruit:
  if (f != "apples") or ("pears"):
     # etc

So python first checks the truth of (f != "apples").  If this is true,
it continues to the body of the if statement.  If this is false,
python checks the truth of ("pears").  Because "pears" is a nonempty
string, it is always true, and so python continues to the body of the
if statement anyway.

You have a few options to correct your code.  Consider the following:

for f in fruit:
  if f == "apples" or f == "pairs":
    print f, "is an apple or a pair."

This will check if f is either "apples" or "pairs".  You can then invert that:

for f in fruit:
  if not (f == "apples" or f == "pairs"):
    print f, "is not an apple or pair."

You could then use DeMorgan's law to convert this to:

for f in fruit:
  if f != "apples" and f != "pairs":
    print f, "is not an apple or pair."

Finally, you have one more option, using the "in" operator:

for f in fruit:
  if f not in ["apples", "pairs"]:
    print f, "is not an apple or pair."

HTH!

-- 
John.


More information about the Tutor mailing list