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?

Nov 2, 2020 in Python by anonymous
• 8,880 points

1 answer to this question.

0 votes

Think of the conditional expression as switching between two values. It is very useful when you're in a 'one value or another' situation, it but doesn't do much else.

If you need to use statements, you have to use a normal if statement instead of a conditional expression.

Keep in mind that it's frowned upon by some Pythonistas for several reasons:

  • The order of the arguments is different from those of the classic condition? a: b ternary operator from many other languages (such as C, C++, Go, Perl, Ruby, Java, Javascript, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behavior use it (they may reverse the argument order).
  • Some find it "unwieldy" since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).
  • Stylistic reasons. (Although the 'inline if' can be really useful, and make your script more concise, it really does complicate your code)
answered Nov 2, 2020 by Gitika
• 65,930 points

Related Questions In Python

+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
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
0 votes
1 answer

What are the ternary conditional operator in Python?

The Ternary Conditional operator was added in ...READ MORE

answered Sep 19, 2018 in Python by SDeb
• 13,290 points
+1 vote
1 answer

Why does x,y = zip(*zip(a,b)) work in Python?

I'm extremely new to Python so this ...READ MORE

answered Aug 23, 2018 in Python by Priyaj
• 58,120 points
0 votes
1 answer

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

You can index into a tuple: (falseValue, trueValue)[test] test needs ...READ MORE

answered Oct 15, 2018 in Python by findingbugs
• 4,790 points
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
0 votes
1 answer

Does Python have a string 'contains' substring method?

You can use the in operator: if "blah" not in ...READ MORE

answered Nov 26, 2020 in Python by Gitika
• 65,930 points