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.
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.
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
expression1andexpression2areTrue, the whole expression evaluates toTrue. - If both
expression1andexpression2areFalse, the whole expression evaluates toFalse. - If
expression1isTrueandexpression2isFalseor vice versa, the whole expression evaluates toFalse.
You can observe this in the following example.
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:
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.
number = 105
if number > 100 and number < 200:
print("{} is between 100 and 200".format(number))
Output:
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.
number = 105
if number > 100:
if number < 200:
print("{} is between 100 and 200.".format(number))
Output:
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.