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,870 points
597 views

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,770 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
2,520 views
0 votes
0 answers

Does Python have a ternary conditional operator?

If Python doesn't have a ternary conditional ...READ MORE

Apr 19, 2022 in Python by Edureka
• 13,620 points
482 views
0 votes
0 answers

Does Python have a ternary conditional operator?

Is there a ternary conditional operator in ...READ MORE

Sep 21, 2022 in Python by Samuel
• 460 points
458 views
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
667 views
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,780 points
673 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
1,405 views
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,770 points
523 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP