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

Robert Kern robert.kern at gmail.com
Fri Jun 14 06:14:16 EDT 2013


On 2013-06-14 10:50, Nick the Gr33k 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' ?
>
>  >>> 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.
>
>  >>> print("k" in (name and month and year))
> True
>  >>>
>
> yes, since expression returns 'ijkl', then the in operator can detect the 'k'
> character within the returned string.
>
> This is all iw ant to know.

This is all you need to read:

   http://docs.python.org/2/reference/expressions.html#boolean-operations

Note the difference between how "or" and "and" each short-circuit. That is why 
the (name or month or year) returns the first truthy value while (name and month 
and year) returns the last truthy value. When "or" finds the first truthy value, 
it can stop looking since the whole expression must be truthy no matter what the 
values are after it. "and" cannot stop looking until it finds a falsy value or 
runs out of values to look at.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list