Python Logical Operators: and, or, not
and: Both Must Be True
Sometimes one condition isn't enough. and joins two conditions, and the result is True only when both are True:
age = 25
has_licence = True
if age >= 18 and has_licence:
print("You can drive.")
else:
print("You can't drive yet.")You can drive.
Change has_licence to False: now it says you can't drive, even though the age is fine.
The and table
| A | B | A and B |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
Think of a door with two locks: it only opens when both keys turn.
Checking a range
and is perfect for "between" questions:
marks = int(input())
if marks >= 0 and marks <= 100:
print("Valid marks")
else:
print("Marks must be 0 to 100")Marks must be 0 to 100
Python also lets you write this range the way you would in maths: 0 <= marks <= 100. It means exactly the same thing, and it's easy to read.
Write both sides in full
A common mistake is if marks >= 0 and <= 100:. Python needs a full comparison on each side of and: marks >= 0 and marks <= 100.
and is True only when both conditions are True.