Eval of expr with 'or' and 'and' within

Cameron Simpson cs at zip.com.au
Fri Jun 14 20:14:03 EDT 2013


On 14Jun2013 12:50, Nikos as SuperHost Support <support at superhost.gr> wrote:
| I started another thread because the last one was !@#$'ed up by
| irrelevant replies and was difficult to jeep track.
| 
| >>> name="abcd"
| >>> month="efgh"
| >>> year="ijkl"
| 
| >>> print(name or month or year)
| abcd
| 
| Can understand that, it takes the first string out of the 3 strings
| that has a truthy value.
| 
| >>> print("k" in (name and month and year))
| True
| 
| No clue. since the expression in parenthesis returns 'abcd' how can
| 'k' contained within 'abcd' ?

Did you print the result of "name and month and year"? It is the
_last_ value (if true at all).  You used "or" in the first example
and "and" in the second.

| >>> print(name and month and year)
| ijkl
| 
| Seems here is returning the last string out of 3 strings, but have
| no clue why Python doing this.

To evaluate an "and" it must test all of them to be true, and it
keeps the last value tested.  (Or False, of course, if they are not
all true, in which case Python stops testing at the first False).

But for what you are doing, "and" and "or" are not good operations.

Something like:

  "k" in (name+month+year)

or

  "k" in name or "k" in month or "k" in year

is a more direct and accurate way to write what I imagine you're trying to do.

Cheers,
-- 
Cameron Simpson <cs at zip.com.au>

No one is completely worthless...  they can always serve as a bad example.



More information about the Python-list mailing list