How does the logical `and` operator work with integers?

Question:

So, I was playing with the interpreter, and typed in the following:

In [95]: 1 and 2
Out[95]: 2

In [96]: 1 and 5
Out[96]: 5

In [97]: 234324 and 2
Out[97]: 2

In [98]: 234324 and 22343243242
Out[98]: 22343243242L

In [99]: 1 or 2 and 9
Out[99]: 1

Initially I thought that it has to do with False and True values, because:

In [101]: True + True
Out[101]: 2

In [102]: True * 5
Out[102]: 5

But that doesn’t seem related, because False is always 0, and it seems from the trials above that it isn’t the biggest value that is being outputted.

I can’t see the pattern here honestly, and couldn’t find anything in the documentation (honestly, I didn’t really know how to effectively look for it).

So, how does

int(x) [logical operation] int(y)

work in Python?

Asked By: oyed

||

Answers:

From the Python documentation:

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.

Which is exactly what your experiment shows happening. All of your x values are true, so the y value is returned.

https://docs.python.org/3/reference/expressions.html#and

Answered By: Dan Lowe

It’s for every item in Python, it’s not dependent on the integer.

not x   Returns True if x is False, False otherwise
x and y Returns x if x is False, y otherwise
x or y  Returns y if x is False, x otherwise

1 is True, so it will return 2

Answered By: Jean Rostan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.