[Tutor] the 'or' attribute

Alan Gauld alan.gauld at blueyonder.co.uk
Wed Dec 10 04:34:19 EST 2003


> How do i use 'or' ? for e.g , i tried
>
>  x = 1 or 2
> print x
>
> it would always print 1, and never two. Why is that?

'or' is a boolean test. It applies a boolean or to both arguments
and returns the boolean result. Boolean values can only be
True or False(which python often represents by non-zero or 0)

Thus "x = 1 or 2" says to python:

If 1 or 2 is true then store 1 in x, if neither 1 or 2 is true
store zero in x.
But since both 1 and 2 are greater than zero python will allways
see '1 or 2' as being true. Thus x always holds 1.

Taking it one step further, Python actually uses something called
short-circuit evaluation of logical (boolean) or. Thus in
evaluating

A or B

because if any one value is true the whole expression is true
Python will first evaluate A and if true it returns A, only if A
is
false does it evaluate B and return B.

So in your case, if you had written

x = 2 or 1

You would find x always had value 2!

We can translate the way Python evaluates an or test into a
function like this:

def or_test(A,B):
    if A: return A
    else: return B


BTW.
If you want to randomly assign either 1 or 2 to x (which seems to
be
what you expected 'or' to do) you would need to use a function
from
the random module, probably randint()

x = random.randint(1,2)

HTH,

Alan G




More information about the Tutor mailing list