Cleaning up conditionals
Jussi Piitulainen
jussi.piitulainen at helsinki.fi
Sat Dec 31 11:29:48 EST 2016
Deborah Swanson writes:
> Is it possible to use some version of the "a = expression1 if
> condition else expression2" syntax with an elif? And for expression1
> and expression2 to be single statements? That's the kind of
> shortcutting I'd like to do, and it seems like python might be able to
> do something like this.
I missed this question when I read the thread earlier. The answer is
simply to make expression2 be another conditional expression. I tend to
write the whole chain in parentheses. This allows multi-line layouts
like the following alternatives:
a = ( first if len(first) > 0
else second if len(second) > 0
else make_stuff_up() )
a = ( first if len(first) > 0 else
second if len(second) > 0 else
make_stuff_up() )
Expression1 and expression2 cannot be statements. Python makes a formal
distinction between statements that have an effect and expressions that
have a value. All components of a conditional expression must be
expressions. A function call can behave either way but I think it good
style that the calls in expresions return values.
More information about the Python-list
mailing list