Table of Contents
In python, we frequently used boolean expressions with conditional statements to implement business logic. In this article, we will discuss how we can use if statements with the AND operator to implement conditional logic in our program.
The and Operator and if Statement in Python
The syntax for the if statement is as follows.
1 2 3 4 5 |
if conditional_expression: statement1 statement2 |
Here, the conditional_expression
is an expression that evaluates to True
or False
. If it evaluates to True, the code inside the if block is executed.
In python, and
is a binary operator that is used to evaluate the combined result of two boolean expressions. The syntax for and
operator in python is as follows.
1 2 3 |
expression1 and expression2 |
Here, expression1
and expression2
should reduce to a boolean value. The result of expression1 and expression2
is decided as follows.
- If both
expression1
andexpression2
areTrue
, the whole expression evaluates toTrue
. - If both
expression1
andexpression2
areFalse
, the whole expression evaluates toFalse
. - If
expression1
isTrue
andexpression2
isFalse
or vice versa, the whole expression evaluates toFalse
.
You can observe this in the following example.
1 2 3 4 5 6 7 8 9 |
expression1 = True expression2 = False expression3 = True expression4 = False print("Result of {} and {} is {}".format(expression1, expression2, expression1 and expression2)) print("Result of {} and {} is {}".format(expression1, expression3, expression1 and expression3)) print("Result of {} and {} is {}".format(expression4, expression2, expression4 and expression2)) |
Output:
1 2 3 4 5 |
Result of True and False is False Result of True and True is True Result of False and False is False |
Application of if Statement with the and Operator in Python
In python, we use the if statement with the AND operator to check multiple conditions in a single if statement as follows.
1 2 3 4 5 |
number = 105 if number > 100 and number < 200: print("{} is between 100 and 200".format(number)) |
Output:
1 2 3 |
105 is between 100 and 200 |
We can also replace nested if statements with If and statements in python. For this, we create a boolean expression using AND operator and boolean expressions of nested if statements as shown below.
1 2 3 4 5 6 |
number = 105 if number > 100: if number < 200: print("{} is between 100 and 200.".format(number)) |
Output:
1 2 3 |
105 is between 100 and 200. |
Here, you can see that we have used two if statements to check if a number is between 100 and 200 or not. In place of the nested for loops, we can use if statement
with and
operator as we saw in the previous example.
Conclusion
In this article, we have discussed if statements with AND operator in python. We also saw how we can replace nested if statements with an if statement with and operator
in python.