If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
YES, python have a ternary operator, here is the syntax and an example code to demonstrate the same :)
You might often find
but this lead to problem when on_true == 0
where you would expect for a normal ternary operator this result
Ternary conditional operator simply allows testing a condition in a single line replacing the multiline if-else making the code compact.
Syntax :
1- Simple Method to use ternary operator:
2- Direct Method of using tuples, Dictionary, and lambda:
3- Ternary operator can be written as nested if-else:
Above approach can be written as:
For versions prior to 2.5, there's the trick:
It can give wrong results when
on_true
has a false boolean value.1Although it does have the benefit of evaluating expressions left to right, which is clearer in my opinion.
1. Is there an equivalent of C’s ”?:” ternary operator?
Ternary Operator in different programming Languages
Here I just try to show some important difference in
ternary operator
between a couple of programming languages.Now you can see the beauty of python language. its highly readable and maintainable.