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 in Python by ana1504.k
• 7,870 points
16 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 by SDeb
• 13,160 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
115 views
0 votes
1 answer

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

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

answered Apr 17, 2018 in Python by Johnathon
• 9,070 points
41 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
• 56,520 points
174 views
+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
• 56,520 points
54 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 173 views
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,160 points
47 views
0 votes
1 answer

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

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

answered May 7 in Python by SDeb
• 13,160 points
38 views