Hit enter after type your search item

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 evaluates as true, the statement in the if statement will execute. Otherwise, the statement in the else part will execute:

See online demo and code

and operator

How ‘and’ operator works?

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.

See online demo and code

Python and

You can see the difference, in 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 case of the first example where we used ‘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.

>See online demo and code

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:

See online demo and code

and &

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

This div height required for enabling the sticky sidebar