“and” in Python Logical Operator

Python has three logical operators. The logical operator “and” in Python is used with two boolean operands and returns a boolean value. It’s also called a short circuit operator or boolean operator. We can’t overload “and” operator in Python. It only works with boolean operands.

Logical Operator – and in Python

Let’s say we have two boolean variables – x and y. There are only four possible variations and two possible outcomes.

xyx and y
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

Based on the above table, the result of and operation is: if x is false, then x, else y.

Let’s look at some simple examples of “and” operator in Python code.

>>> x = True
>>> y = False
>>> x and y
False
>>> y = True
>>> x and y
True

Bitwise & (and) Operator

The bitwise and operator in Python work only with integers. The operands are converted to binary and then “and” operation is performed on every bit. Then, the value is converted back to decimal and returned.

If both bits are 1, then & operator returns 1, else 0. Let’s look at some examples.

>>> 10 & 5
0
>>> 10 & -5
10

Explanation:

10 = 1010
5 = 0101
-5 = 1011

1010 & 0101 = 0000 = 0
1010 & 1011 = 1010 = 10

Summary

Boolean operator “and” in Python works with boolean operands. We can’t overload this or use it with non-boolean values. We also have bitwise and operator, which work with only integers.

What’s Next?

Resources