You may use the ‘and’ operator in the if statement to evaluate multiple expressions.
See the following section for examples to learn how it works.
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 are evaluated 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:
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)
Output:
- 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, the 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")
Result:
You see, two variables are evaluated as true, while the third is false so the else part is executed:
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")
output:
You can see, it produced the same result as using the ‘and’ operator.