What is ‘and’ operator in Python?

In Python, the ‘and’ is a logical operator that evaluates as True if both the operands (x and y) are True.

You may use this in the if statement for evaluating multiple expressions. See the following section for examples of using the ‘and’ operator.

Python ‘and’ example with if statement

In this example, two int type variables are declared and their values are checked in the if statement with and operator. If both evaluate as true, the statement in the if statement will execute. Otherwise, the statement in the else part will execute:

#A demo of using 'and' operator

int_a = 10

int_b = 20

if (int_a== 10) and (int_b == 20):

    print("True")

else:

    print("False")

Output:

and operator

How does ‘and’ operator work?

This is to be noted that ‘and’ and ‘or’ return the last evaluated argument. In the case of x and y expressions, if x is false, its value is returned, otherwise, y is evaluated. See a demonstration below.

#A demo of using 'and' operator

x = False

y = True



a = True

b = 30



# x is False so b in not evaluvated

print(x and y)


# a is True so b is evaluvated

print(a and b)

Python and

You can see the difference, in the case of x and y, the x is false so its value is returned. In the second case, the ‘a’ is True so ‘b’ is also evaluated and its value is returned.

That means, in the case of the first example where we used the ‘and’ operator in the if statement, the first expression is checked i.e.  (int_a == 10). As it was True, so it kept on checking the (int_b == 20).

Using multiple ‘and’ operators including a string

For this example, the ‘and’ is used twice in the if statement. Two variables are int type while the third is a string variable. Their values are checked in the if statement and if all are True, the print function inside the if statement will execute, otherwise, else part will execute.

int_a = 11

int_b = 33

str_c = 'Python'



if (int_b== 33) and (int_a == 20) and (str_c == 'Python'):

    print("All are True")

else:

    print("All or anyone is False")

if and

You see, two variables are evaluated as true, while the third is false so else part executed and it displayed:

All or anyone is False

The bitwise operator & (and) example

There is also a bitwise operator ‘&’ (Bitwise AND) that operates bit by bit. See an example below of using the & operator in if statement:

#A demo of using '&' operator



int_a = 10

int_b = 55

if (int_a >= 3) & (int_b < 100):

    print("Both are True")

else:

    print("Both or one is False")

and &

You can see, it produced the same result as using the ‘and’ operator.

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we unravel the mysteries of coding together!