Python Logical Operators
Logical operators are used to combine conditional statements and return Boolean values (True
or False
). They are fundamental in controlling the flow of a program by evaluating multiple conditions.
Python has three logical operators:
Operator | Description | Example |
---|---|---|
and |
Logical AND | Returns True if both conditions are True |
or |
Logical OR | Returns True if at least one condition is True |
not |
Logical NOT (negation) | Reverses the Boolean value |
1. and
Operator
The and
operator returns True
only if both conditions are True
. If either one or both are False
, it returns False
.
Syntax:
condition1 and condition2
Example:
x = 10
print(x > 5 and x < 15) # True, because 10 > 5 AND 10 < 15
print(x > 5 and x > 20) # False, second condition is False
Explanation:
x > 5 and x < 15
isTrue
because both parts are true.x > 5 and x > 20
isFalse
because the second part (x > 20
) is false.
2. or
Operator
The or
operator returns True
if at least one of the conditions is True
. It only returns False
if both conditions are False
.
Syntax:
condition1 or condition2
Example:
x = 10
print(x > 5 or x > 20) # True, because first condition is True
print(x < 5 or x > 20) # False, both conditions are False
Explanation:
x > 5 or x > 20
isTrue
becausex > 5
is true.x < 5 or x > 20
isFalse
because both conditions are false.
3. not
Operator
The not
operator reverses the Boolean value of a condition.
Syntax:
not condition
Example:
x = 10
print(not x > 5) # False, because x > 5 is True, and `not` reverses it
print(not x < 5) # True, because x < 5 is False, and `not` reverses it
Combining Logical Operators
You can combine and
, or
, and not
to form complex conditions.
Example:
x = 10
y = 20
if x > 5 and (y < 15 or not y == 20):
print("Condition met")
else:
print("Condition not met")
Explanation:
x > 5
is Truey < 15
is Falsenot y == 20
meansnot True
→ False(y < 15 or not y == 20)
→False or False
→ False- So
True and False
→ False, so the else block runs.
Truth Table Summary
A | B | A and B | A or B | not A |
---|---|---|---|---|
True | True | True | True | False |
True | False | False | True | False |
False | True | False | True | True |
False | False | False | False | True |
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.