Introduction
Logical operators are essential in programming as they help in decision-making based on multiple conditions. In Python, logical operators (and
, or
, not
) allow you to combine or modify conditions to control the flow of your code.
This guide will explain:
- What logical operators are
- How to use
and
,or
, andnot
in Python - Real-world examples (like bank loan eligibility checks)
- Differences between logical and boolean operators
What Are Logical Operators?
Logical operators evaluate multiple conditions and return True
or False
based on the given logic. They are commonly used in:
- Conditional statements (
if-else
) - Loops (
while
,for
) - Boolean expressions
Python has three main logical operators:
and
→ ReturnsTrue
only if both conditions are true.or
→ ReturnsTrue
if at least one condition is true.not
→ Reverses the boolean result (True
becomesFalse
and vice versa).
1. The and
Operator
The and
operator checks if all given conditions are True
.
Example:
age = 25
income = 50000
# Check if age is above 18 AND income is above 30000
if age > 18 and income > 30000:
print("Eligible for loan")
else:
print("Not eligible")
Output:
Eligible for loan
Truth Table for and
Condition 1 | Condition 2 | Result |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
2. The or
Operator
The or
operator returns True
if at least one condition is True
.
Example:
has_passport = True
has_voter_id = False
# Check if either passport or voter ID is available
if has_passport or has_voter_id:
print("Allowed to apply")
else:
print("ID proof required")
Output:
Allowed to apply
Truth Table for or
Condition 1 | Condition 2 | Result |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
3. The not
Operator
The not
operator reverses the boolean value.
Example:
is_raining = False
if not is_raining:
print("You can go outside!")
else:
print("Stay indoors.")
Output:
You can go outside!
Truth Table for not
Condition | not Condition |
---|---|
True | False |
False | True |
Logical vs. Boolean Operators
- Logical Operators (
and
,or
,not
) → Work with boolean values (True
/False
) to make decisions. - Boolean Operators → A broader term that includes logical operators but also covers bitwise operations (
&
,|
,~
).
In Python, logical operators are often called boolean operators because they operate on boolean values.
Real-World Use Case: Bank Loan Eligibility
Let’s apply logical operators to a real-world scenario:
age = 22
annual_income = 450000
# Check if age >= 18 AND income >= 300000
if age >= 18 and annual_income >= 300000:
print("Loan Approved!")
else:
print("Loan Rejected.")
Output:
Loan Approved!
Conclusion
Logical operators (and
, or
, not
) are fundamental in Python for controlling program flow based on conditions.
Key Takeaways:
✔ and
→ Both conditions must be True
.
✔ or
→ At least one condition must be True
.
✔ not
→ Inverts the boolean value.