Q from python tut...

Deryk Barker dbarker at camosun.bc.nospam.ca
Sat May 29 14:18:32 EDT 1999


Gordon McMillan (gmcm at hypernet.com) wrote:
: prasad writes:
: > 
: > I am learning python using the standard tut that came with the
: > distri. I know perl a little bit. Here are some of the things that I
: > found confusing till section 5.5.
: > 
: > 
: > val = '' or 'aa' or 'bb'
: > val gets the value 'aa'
: > 
: > shouldn't the expr '' or 'aa' or 'bb' evaluate to 0 or 1 and hence
: > val getting the value of 0 or 1.
: 
: Python has a protocol for determining whether an object considers 
: itself "true" or not. Collections (tuples, lists, dicts and 
: strings) are true if they're non-empty. The fact that val gets bound 
: to the first "true" thing in the RHS is very handy, if somewhat 
: surprising at first.

And is a direct result of the short-circuit evaluation being used.

on the basis that true or X =  true
		  false or X = X
and
		  false and X = false
		  false or X  = X

As soon as you find true (false) when evaluating an or (and) then you
can stop and not bother to evaluate any more of the expression.

You need to watch for side-effects...


Similarly any non-zero numeric value is true, and short-circuiut
evaluation is also used, so that the value of

	2 or 5

is 2 whereas the value of

	0 or 5

is 5.

-- 
|Deryk Barker, Computer Science Dept. | Music does not have to be understood|
|Camosun College, Victoria, BC, Canada| It has to be listened to.           |
|email: dbarker at camosun.bc.ca         |                                     |
|phone: +1 250 370 4452               |         Hermann Scherchen.          |





More information about the Python-list mailing list