Ternary operator in Pyton
One of the most annoying things about Python is the lack of a ternary operator. You know, that whole ? : that allows you to set conditional values in a single line:
If Python is your first language, you'll never even notice it's gone. But if you've used other languages, most of them have a ternary operator. And they have it for a reason, it fills a very nice niche for setting conditionals values with the minimal amount of code.
Thankfully as of version 2.5 Python now has something that is not quite the ternary operator, but it fills the same need and one could argue -- and I'm sure several have -- that it's actually a little better the way the implemented since it's more of a single-line if-else statement which is a little easier to understand if you are not use to the ternary operator. It goes something like this:
or in actual usage:
which will return the value 'thisStatementIsTrue'.
So if you've upgraded to version 2.5 of Python, congratulations you now have something that can be used as a ternary operator. If you have not, you are still going to be writing some extra code to assign condition values.
cond ? valueIfConditionIsTrue : valueIfConditionIsFalse
If Python is your first language, you'll never even notice it's gone. But if you've used other languages, most of them have a ternary operator. And they have it for a reason, it fills a very nice niche for setting conditionals values with the minimal amount of code.
Thankfully as of version 2.5 Python now has something that is not quite the ternary operator, but it fills the same need and one could argue -- and I'm sure several have -- that it's actually a little better the way the implemented since it's more of a single-line if-else statement which is a little easier to understand if you are not use to the ternary operator. It goes something like this:
valueIfConditionIsTrue if condition else valueIfConditionIsFalse
or in actual usage:
'thisStatementIsTrue' if 1 == 1 else 'thisStatementIsFalse'
which will return the value 'thisStatementIsTrue'.
So if you've upgraded to version 2.5 of Python, congratulations you now have something that can be used as a ternary operator. If you have not, you are still going to be writing some extra code to assign condition values.
| Rating: | 100% positive, 1 Vote |
| Categories: | Python programming shortcut |
| Added: | on Jul 11, 2008 at 9:36 pm |
| Added By: | an anonymous user |

