Does Python have a ternary conditional operator like java?

+1 vote
asked Aug 1 by Hitesh Garg (167 points)  

Ternary syntax (expr ? val1 : val2) like other languages is not supported in python because it gives errors when I used it.
Is there any ternary equivalent in python in which value to a variable can be assigned based on true/false of a codition.

1 Answer

+1 vote
answered 4 days ago by Rahul Singh (253 points)  
selected 4 days ago by Hitesh Garg
Best answer

Yes there is one but you are facing the difficulty because the sytax is not similar to other languages like C, Java etc. and this is the reason the syntax mentioned below is not liked by many programmers.

So it goes like this

# Syntax
# val1 if expr else val2

>>> y = 1
>>> x = 1 if y==2 else 2
>>> print(x)

>>> 'true' if True else 'false'
>>> 'true' if False else 'false'

Official docs -

36 questions

24 answers


17 users

Welcome to Codingeek Q&A, where you can ask questions and receive answers from other members of the community.