?: in Python
Kent Johnson
kent at kentsjohnson.com
Thu Dec 15 23:03:45 EST 2005
Andy Leszczynski wrote:
> How can do elegantly in Python:
>
> if condition:
> a=1
> else:
> a=2
>
> like in C:
>
> a=condition?1:2
>
a = condition and A or B
is concise but will fail if A can evaluate as false, e.g.
a = condition and None or 2 # won't do what you want
I tend to use 'condition and A or B' if I'm sure A won't be false, otherwise just write
out the if / else.
Kent
More information about the Python-list
mailing list