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,750 points
28 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,750 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 in Python by Waseem
• 4,160 points
12 views
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 in Python by anonymous
164 views
0 votes
1 answer

How to print first character of each word in upper case of a string in Python

You can use split() using space as ...READ MORE

answered Jun 1, 2018 in Python by george
• 200 points
1,551 views
0 votes
1 answer

what does a conditional operator in python do?

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

answered May 2 in Python by Mohammad
• 2,820 points
36 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 169 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
113 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,710 points
1,178 views