X and Y or Z - ternary operator

0 votes
In Java or C we have <condition> ? X : Y, which translates into Python as X if <condition> else Y.

But there's also this little trick: <condition> and X or Y.

I know that it is equivalent to the aforementioned ternary operators, but I find it difficult to grasp how and or operators are able to produce the correct result. Can anyone explain the logic?
May 23, 2019 in Python by ana1504.k
• 7,910 points
1,781 views

1 answer to this question.

0 votes
According to the docs:

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

So, True and 0 or 1 evaluates the first argument of the and operator, which is True. Then it returns the second argument, which is 0.

Since the True and 0 returns false value, the or operator returns the second argument (i.e. 1)
answered May 23, 2019 by SDeb
• 13,300 points

Related Questions In Python

0 votes
1 answer

How to change the “tick frequency” on x or y axis in matplotlib?

You could explicitly set where you want ...READ MORE

answered Jan 5, 2021 in Python by Gitika
• 65,770 points
18,076 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
2,520 views
0 votes
1 answer

what are "and" and "or" operators in Python?

AND - True if both the operands ...READ MORE

answered Apr 18, 2018 in Python by Johnathon
• 9,090 points
868 views
+1 vote
1 answer

What is the difference between range and xrange functions in Python 2.X?

xrange only stores the range params and ...READ MORE

answered Aug 22, 2018 in Python by Priyaj
• 58,020 points
2,438 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,466 views
0 votes
1 answer
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,300 points
753 views
0 votes
1 answer

Python 3.x on python(x,y)?

You can make Python 2 behave the ...READ MORE

answered May 7, 2019 in Python by SDeb
• 13,300 points
2,146 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