Jussi Piitulainen wrote: > Sent: Saturday, December 31, 2016 8:30 AM > 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.
Your second alternative is exactly what I was thinking should be possible in python, but I couldn't figure out how to do it. I'm rewriting the little function I wrote to use this form. Thanks also for the explanation of why expressions work in terniaries, but statements don't, and what the difference between statements and expressions is. -- https://mail.python.org/mailman/listinfo/python-list