To simulate construct of other language does Python have a ternary conditional operator

0 votes
If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
Oct 15, 2018 in Python by findingbugs
• 4,790 points
134 views

1 answer to this question.

0 votes

You can index into a tuple:

(falseValue, trueValue)[test]

test needs to return True or False.
It might be safer to always implement it as:

(falseValue, trueValue)[test == True]

or you can use the built-in bool() to assure a Boolean value:

(falseValue, trueValue)[bool(<expression>)]
answered Oct 15, 2018 by findingbugs
• 4,790 points

Related Questions In Python

0 votes
0 answers

What does a ternary conditional operator do in python?

Can you give an example using a ...READ MORE

Jun 17, 2019 in Python by Waseem
• 4,540 points
137 views
0 votes
0 answers
0 votes
1 answer
0 votes
2 answers

How to calculate square root of a number in python?

calculate square root in python >>> import math ...READ MORE

answered Apr 2, 2019 in Python by anonymous
1,912 views
0 votes
1 answer

Does Python have a ternary conditional operator?

Think of the conditional expression as switching ...READ MORE

answered Nov 2, 2020 in Python by Gitika
• 65,950 points
91 views
0 votes
2 answers
0 votes
1 answer

what does a conditional operator in python do?

Conditional operators in python is same as ...READ MORE

answered May 2, 2019 in Python by Mohammad
• 3,230 points
246 views
+4 votes
6 answers

Does Python have a ternary conditional operator like C does?

Yes, the syntax is: a if condition else ...READ MORE

answered Apr 13, 2018 in Python by Nietzsche's daemon
• 4,260 points
642 views
+2 votes
2 answers

How to make a laplacian pyramid using OpenCV python?

down voteacceptTheeThe problem is that you're iterating ...READ MORE

answered Apr 3, 2018 in Python by charlie_brown
• 7,780 points
3,503 views