Question About Logic In Python

Dan Bishop danb_83 at
Mon Sep 19 03:04:44 CEST 2005

James H. wrote:
> Greetings!  I'm new to Python and am struggling a little with "and" and
> "or" logic in Python.  Since Python always ends up returning a value
> and this is a little different from C, the language I understand best
> (i.e. C returns non-zero as true, and zero as false), is there anything
> I should be aware of given Python's different approach?  Namely any
> pitfalls or neat tricks that make the Python approach cool or save my
> butt.

The most common use of this feature is "x = x or default_val" as a
shorthand for "if not x: x = default_val".

Also, you can emulate C's ternary operator (cond ? t : f) with
(cond and [t] or [f])[0].

More information about the Python-list mailing list