π§ Python Logical Operators β Building Smart Conditions
Introduction π
Logical operators allow you to combine multiple conditions and make more complex decisions in your programs. They return True or False just like comparison operators.
Note
π‘ Logical operators are used heavily in if statements, loops, validations, and expressions.
1. List of Logical Operators π
| Operator | Meaning | Example |
|---|---|---|
| and | True if both conditions are True | x > 5 and x < 10 |
| or | True if at least one condition is True | x > 5 or x == 5 |
| not | Reverses the condition | not (x == 5) |
2. The AND Operator π’
and returns True only if **both** expressions are True.
logical_and.py
age = 20
country = "India"
print(age > 18 and country == "India") # True
print(age > 18 and country == "USA") # FalseNote
βοΈ Use and when multiple conditions must be met.
3. The OR Operator π‘
or returns True if **any one** condition is True.
logical_or.py
marks = 65
print(marks > 70 or marks >= 60) # True
print(marks > 70 or marks < 40) # FalseNote
βοΈ Use or when one of several conditions is enough.
4. The NOT Operator π
not reverses the truth value.
logical_not.py
is_active = True
print(not is_active) # False
print(not (5 > 2)) # False
print(not (5 < 2)) # TrueNote
βοΈ Use not to invert conditions.
5. Combining Logical Operators π
You can combine multiple logical expressions.
combined_logical.py
age = 22
citizen = True
has_id = False
if age >= 18 and citizen and (has_id or age > 21):
print("Access granted")
else:
print("Access denied")6. Logical Operators With Comparisons π
logical_compare.py
x = 15
print(x > 10 and x < 20) # True
print(x < 10 or x == 15) # True
print(not (x == 15)) # False7. Logical Operators With Strings π€
logical_strings.py
name = "Sathish"
print(name.startswith("S") and len(name) > 5) # True
print(name.endswith("h") or name.endswith("z")) # True8. Logical Operators With Boolean Values βοΈ
bool_values.py
print(True and False) # False
print(True or False) # True
print(not False) # True9. Truthy and Falsy Values π§©
Python treats some values as False even if they are not boolean.
- Falsy: 0, "", [], , None, False
- Truthy: any non-empty or non-zero value
truthy_falsy.py
print(bool(0)) # False
print(bool("hi")) # True
print(bool([])) # False10. Real-World Example π
real_world_example.py
username = input("Enter username: ")
password = input("Enter password: ")
if username == "admin" and password == "1234":
print("Login successful")
else:
print("Access denied")Conclusion π
>>βLogical operators allow your program to think β combine conditions and build powerful logic!β π₯
You now understand logical operators in Python. Want to continue with Bitwise Operators, Conditional Statements, Loops, or Expressions? Just tell me the next topic! π