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

Alex Hall mehgcap at gmail.com
Fri Dec 10 02:23:24 CET 2010


Thanks to all for the quick responses. Python always surprises me with
its shortcuts...

On 12/9/10, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "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/
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap


More information about the Tutor mailing list