Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the logical `and` operator work with integers? [duplicate]

Tags:

python

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?

like image 660
oyed Avatar asked Apr 04 '18 18:04

oyed


People also ask

What are the 2 logical operators?

Common logical operators include AND, OR, and NOT.

How does && operator work in C?

The logical AND operator ( && ) returns true if both operands are true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool . Logical AND has left-to-right associativity.

How does logical AND work in C?

The logical-AND operator produces the value 1 if both operands have nonzero values. If either operand is equal to 0, the result is 0. If the first operand of a logical-AND operation is equal to 0, the second operand isn't evaluated. The logical-OR operator performs an inclusive-OR operation on its operands.

How do the different logical operators work together?

Logical operators combine relations according to the following rules: The ampersand (&) symbol is a valid substitute for the logical operator AND . The vertical bar ( | ) is a valid substitute for the logical operator OR . Only one logical operator can be used to combine two relations.


2 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

like image 131
Dan Lowe Avatar answered Sep 29 '22 17:09

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

like image 33
Jean Rostan Avatar answered Sep 29 '22 18:09

Jean Rostan