A certainl part of an if() structure never gets executed.

R. Michael Weylandt michael.weylandt at gmail.com
Fri Jun 14 04:24:18 EDT 2013


On Fri, Jun 14, 2013 at 9:03 AM, Nick the Gr33k <support at superhost.gr> wrote:>
>>>> 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' ?

No it's not. See both above (where you use 'or' instead) and below
where _you yourself_ show that it's not 'abcd.'

Now read: https://en.wikipedia.org/wiki/Short-circuit_evaluation
noting especially the specified behavior for Python. If you find it
too technical, google for other uses of the terms.

>
>>>> 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.

Think about basic logic: 'or' means 'is at least one true?' so Python
only has to look at the first 'truthy value'. 'and' means 'are they
all true?' so Python has to look at all the values, ending up with the
last one, unless a 'falsey value' is found before.

Michael



More information about the Python-list mailing list