and keyword is a logical operator used to combine two or more conditions. It returns True only if all the conditions are True. It is commonly used in if statements to check multiple conditions together.
x = 10
y = 5
if x > 0 and y > 0:
print("Both numbers are positive")
Output
Both numbers are positive
Explanation: condition x > 0 and y > 0 is True because both x and y are greater than 0. Therefore, the print() statement is executed.
Syntax
The general syntax of the and keyword is shown below:
condition1 and condition2
Or, it can be used inside an if statement as follows:
if condition1 and condition2:
# code
Truth Table
The following truth table shows the result of the and keyword for different combinations of Boolean values:
| First Condition | Second Condition | Result |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
Explanation: and keyword returns True only when both conditions are True. If either one or both conditions are False, the result is False.
In Conditional Statements
The and keyword is commonly used in if statements when you want multiple conditions to be true before executing a block of code.
age = 20
income = 5000
if age > 18 and income > 3000:
print("Eligible for a credit card")
Output
Eligible for a credit card
Explanation: The message is printed because both conditions (age > 18 and income > 3000) are True.
In Loops
The and keyword can also be used in loops to continue execution only while multiple conditions remain true.
a = 1
while a < 10 and a % 2 != 0:
print(a)
a += 2
Output
1 3 5 7 9
Explanation: The loop runs only while a is less than 10 and a is an odd number. When either condition becomes False, the loop stops.
With Boolean Values
The and keyword can be used directly with Boolean values. It returns True only if both operands are True.
a = True
b = False
print(a and b)
print(a and True)
print(False and False)
Output
False True False
Explanation:
- a and b returns False because b is False.
- a and True returns True because both values are True.
- False and False returns False because both operands are False.
With Comparison Operators
The and keyword is often used with comparison operators to check whether a value satisfies multiple conditions at the same time.
marks = 85
if marks >= 80 and marks <= 100:
print("Excellent")
Output
Excellent
Explanation: The value of marks is 85, which is greater than or equal to 80 and less than or equal to 100. Since both conditions are True, the print() statement is executed.