Logical operators are used to combine conditional statements. In Python, there are three main logical operators: and, or, and not. These are most commonly used in decision-making and boolean expressions.
Let’s explore how each operator behaves with real-world examples.
Example 1: Using and with Booleans
a = True
b = True
print(a and b)Returns True only when both conditions are True.
Example 2: Using and in a Condition
age = 25
has_license = True
if age >= 18 and has_license:
print("You can drive")Both conditions must be true for the message to be printed.
Example 3: Using or with Booleans
is_raining = False
has_umbrella = True
print(is_raining or has_umbrella)Returns True if at least one condition is True.
Example 4: Using or in a Condition
user_role = "editor"
if user_role == "admin" or user_role == "editor":
print("Access granted")If either condition is true, access is granted.
Example 5: Using not to Invert
is_logged_in = False
if not is_logged_in:
print("Please log in first")The not operator inverts the boolean value.
Example 6: Complex Condition with and and or
age = 20
country = "India"
has_voter_id = False
if (age >= 18 and country == "India") or has_voter_id:
print("Eligible to vote")This shows how complex logical expressions can be built using parentheses.
Example 7: Chaining Conditions
num = 15
if num > 0 and num < 100:
print("Number is between 1 and 99")Logical operators are commonly used in range checks.
Example 8: Logical Operators with Strings
username = ""
if not username:
print("Username cannot be empty")An empty string is treated as False, so not username becomes True.
Example 9: Using or for Defaulting
input_name = ""
name = input_name or "Guest"
print("Welcome,", name)If input_name is empty, "Guest" is used as a fallback.
Example 10: Logical Expressions Return Values
a = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # FalseLogical expressions return boolean values that can be used or stored.
Summary
and: ReturnsTrueif both operands areTrue.or: ReturnsTrueif at least one operand isTrue.not: Inverts the Boolean value.- Use parentheses to group expressions and avoid confusion.
- Logical operators are essential for flow control and decision-making.
Understanding logical operators allows you to build smart, decision-driven code and write powerful conditions in Python.
