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

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


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

not x   Returns True if x is True, 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

Tags:

Python