Python Logical Operators
To join conditional statements together, Python gives you three logical operators:
and- True only when the two statements are both trueor- True when at least one statement is truenot- Flips the result, so true becomes False and false becomes True
The and Operator
The and operator joins two conditions and demands that both of them hold. If either one fails, the whole expression is False.
Example
a is above b AND c is above a:and operator to test if a is greater than b AND c is greater than a.
Output: complete Python program
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
The or Operator
The or operator also joins two conditions, but it is easier to satisfy. A single true condition is enough to make the whole expression True.
Example
a is above b OR above c:or operator to test if a is greater than b OR a is greater than c.
Output: complete Python program
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
The not Operator
The not operator works on one condition and turns its result into the opposite.
Example
a is NOT above b:not operator to test if a is NOT greater than b.
Output: complete Python program
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Combining Multiple Operators
A single expression may contain several logical operators. Python handles them in a fixed order: not comes first, followed by and, and finally or.
Example
and, or and not together:and, or, and not operators to check if a discount applies based on age, student status, and discount code.
Output: complete Python program
age = 25
is_student = False
has_discount_code = True
if (age < 18 or age > 65) and not is_student or has_discount_code:
print("Discount applies!")
Truth Tables
These tables show the result of each operator for every pair of values:
Truth Table for the and Operator
| Condition 1 | Condition 2 | Result |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
Truth Table for the or Operator
| Condition 1 | Condition 2 | Result |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
Using Parentheses for Clarity
When an expression mixes several logical operators, parentheses show what you mean and decide what gets evaluated first.
Example
Output: complete Python program
temperature = 25
is_raining = False
is_weekend = True
if (temperature > 20 and not is_raining) or is_weekend:
print("Great day for outdoor activities!")
More Examples
Example
Output: complete Python program
username = "Tobias"
password = "secret123"
is_verified = True
if username and password and is_verified:
print("Login successful")
else:
print("Login failed")
Example
and operator to check if a score is within a valid range (0-100).
Output: complete Python program
score = 85
if score >= 0 and score <= 100:
print("Valid score")
else:
print("Invalid score")