[Tutor] OR operator?

Alan Gauld alan.gauld at freenet.co.uk
Thu Apr 6 13:46:37 CEST 2006


> I'm trying with this operator, could it possible?
> 
> fruit1 = 'apple'
> fruit2 = 'orange'
> 
> fruits = fruit1 or fruit2
> 
> is 'orange' = fruits ?

Why not just try it at the python prompt?!

And you would find that no, fruits = 'apple'
(The order is because fruits is a name which references a 
value. orange is a value so cannot reference anything else, so 
'orange' = fruits is actually an impossible concept!).

The reason for the result is the way Python evaluates 'or' expressions.
Python considers non-empty strings (like 'apple') to be true.
Python also evaluates an 'or' by evaluating the first element 
and, if it is true then it doesn't bother evaluating the second element
since the 'or' must be true if the first part is true. This is known 
as "short-circuit evaluation".

If you did 

fruit3 = ""
fruits = fruit3 or fruit2

this time fruits would equal 'orange' because the first item 
was an empty string which Python considers to be false 
so it had to evaluate the second item.

Finally, it could be argued that the 'or' should return 'true' or 'false 
but because Python considers values to be either true or false it 
just returns the value. I suspect that if boolean values had been 
in Python at the beginning the result would be different but 
they weren't and it isn't! :-)

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list