Sumitava Mukherjee <[EMAIL PROTECTED]> wrote:

>Hi all,
>I am a novice programmer in Python.
>Please could you explain me the results (regarding logical operators).
>
>I get this:
>
>>>> print bool('God' and 'Devil')
>True
>
>[This is ok because (any) string is True, so; (True and True) gives
>True]

Your statement is accurate, but that's not why it returns true.

>>>> print('God' and 'Devil')
>Devil

Right.  And bool('Devil') is True, because a non-empty string is a true
value.

>[This is what I don't get ]
>and for that matter,I also checked out this:
>
>>>> 01 and 10
>10
>
>What is python doing when we type in ('God' and 'Devil') or key in (01
>and 10) ?

"and" and "or" are a bit more than logical operators.  The exact definition
of "x and y" is "if x has a false value, return x, otherwise return y".  If
both sides are booleans, this does exactly what you expect.

Similarly, "x or y" is actually done as "if x has a true value, return x,
otherwise return y".

This allows for one of the cuter Python hacks:
    xxx = x and y or z
which is essentially the same as the C ternary operator:
    xxx = x ? y : z;
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to