🧠 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 πŸ“‹

OperatorMeaningExample
andTrue if both conditions are Truex > 5 and x < 10
orTrue if at least one condition is Truex > 5 or x == 5
notReverses the conditionnot (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")     # False

Note

βœ”οΈ 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)    # False

Note

βœ”οΈ 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))     # True

Note

βœ”οΈ 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))       # False

7. 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")) # True

8. Logical Operators With Boolean Values βœ”οΈ

bool_values.py

print(True and False)   # False
print(True or False)    # True
print(not False)        # True

9. 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([]))       # False

10. 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! 😊