What are Logical Operators?
Logical operators in Python allow you to combine multiple conditions and make smarter decisions in your code! Think of them as the brain of your program—they help you decide what happens next!
Python has three logical operators:
Operator | Meaning | Example |
---|---|---|
and |
True if both conditions are true | True and False → False |
or |
True if at least one condition is true | True or False → True |
not |
Reverses the condition | not True → False |
The and
Operator
and
returns True
only if both conditions are True.
x = 10
y = 5
print(x > 5 and y < 10) # True (both conditions are true)
print(x > 15 and y < 10) # False (one condition is false)
🎠Real-life Example:
- If you have money AND the store is open, you can buy candy!
has_money = True
store_open = False
if has_money and store_open:
print("You can buy candy!")
else:
print("No candy for you!")
The or
Operator
or
returns True
if at least one condition is True.
x = 10
y = 5
print(x > 5 or y > 10) # True (one condition is true)
print(x > 15 or y > 10) # False (both are false)
Real-life Example:
- If it’s Saturday OR Sunday, you don’t have to go to work!
day = "Sunday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")
else:
print("Back to work... ")
The not
Operator
not
reverses the condition (True becomes False, and vice versa).
x = True
y = False
print(not x) # False
print(not y) # True
Real-life Example:
- If you’re NOT hungry, you won’t eat.
hungry = False
if not hungry:
print("No food for me!")
else:
print("Feed me!")
Combining Logical Operators
You can mix and
, or
, and not
together for complex conditions!
x = 10
y = 5
z = 20
print((x > 5 and y < 10) or z == 25) # True (first part is True)
print(not (x > 5 and y < 10)) # False (negating True)
Order of Operations:
not
is evaluated first.and
is evaluated second.or
is evaluated last.
Use parentheses ()
to control the order and avoid confusion!
Summary
Operator | Meaning | Example |
---|---|---|
and |
True if both conditions are True | True and False → False |
or |
True if at least one condition is True | True or False → True |
not |
Reverses the condition | not True → False |
Now you're a master of logical operations! Time to write some smart Python code!
0 Comments