[Tutor] 'or' in assignment (not if statement)?

Alan Gauld alan.gauld at btinternet.com
Fri Dec 10 02:07:02 CET 2010


"Alex Hall" <mehgcap at gmail.com> wrote 

> val=val or 1

> I am guessing that val is an int. If val==0, the 'or' kicks in and
> val=1, else the or is not needed and val=val. Am I close? 

Yes this is a combination of what is known as short circuit 
evaluation of boolean expressions and a quirk of Python that 
returns the actual value of something that is being treated as 
a boolean.

There is a section on this in the Functional Programming 
topic in my tutor which explains and illustrates in much 
more detail.

This particular trick is now deprecated in favour of the new 
conditional expressiion, so your code would now be written as:

val = val if val else 1

> Can other words or symbols be used in contexts where one 
> would not normally think of them?

See my tutor, it shows how and can be used in similar ways...

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list