9 ms·
You can have a one-line "if" statement [1]: if a == 42: print "Yes" ; do_stuff() It's true that you cannot have a "else" statement on the same line, however
by ronnix 16y ago
You can have a one-line "if" statement [1]:
if a == 42: print "Yes" ; do_stuff()
It's true that you cannot have a "else" statement on the same line, however.
But in some cases, you could use a conditional expression instead [2]:
x = f() if a == 42 else g()
[1] http://docs.python.org/reference/compound_stmts.html http://docs.python.org/reference/compound_stmts.html
[2] http://docs.python.org/reference/expressions.html#conditional-expressions http://docs.python.org/reference/expressions.html#conditiona...
- nivertech 16y agoin this case plain old C syntax is much more readable: x = (a==42) ? f() : g();
- orangecat 16y agoIn this case I think the PEP8 spacing guidelines are counterproductive: f() if a==42 else g() looks much more readable to me than f() if a == 42 else g()
- pyre 16y agoI think that it's much more readable due to familiarity more than anything else. The C syntax for the ternary operator was the one thing that it took me the longest time to get used to when learning to program. I usually just ignored it because it was too hard to remember what it did. That said, I can easily read it now, but I still feel that the Python syntax is more understandable. Which is more readable: > condition ? value1 : value2 or > value1 if condition else value2 Maybe the latter is just more readable to me because I'm used to reading Perl all day long that looks like: > die unless condition; > return true if condition; > return false > if condition1 && condition2 && condition3; That said, I'm also used to reading: > return condition1 ? value1 > : condition2 ? value2 > : condition3 ? value3 > : value4; and I still find the Python ternary operator more readable: > return value1 if condition1 else > value2 if condition2 else > value3 if condition3 else > value4
- j_baker 16y agoPersonally, I still have to think about what the ternary operator means every time I see it. It's just so nonobvious.
- ronnix 16y agoYou can also write it this way, which is more similar to C: x = (a==42) and f() or g()
- deleted 16y ago[deleted]