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 1,416 views

## 1 answer to this question.

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)
• 13,300 points

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

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

## Does Python have a ternary conditional operator like C does?

Yes, the syntax is: a if condition else ...READ MORE

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

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

+1 vote

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

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

## how do i change string to a list?

suppose you have a string with a ...READ MORE

## how can i randomly select items from a list?

You can also use the random library's ...READ MORE

+1 vote

## how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE