0
0
Pythonprogramming~5 mins

Logical operators in Python

Choose your learning style9 modes available
Introduction

Logical operators help us combine or change true/false values to make decisions in programs.

Checking if two conditions are both true, like if a door is locked AND the alarm is on.
Deciding if at least one condition is true, like if it is raining OR snowing to wear a coat.
Reversing a condition, like if a light is NOT on, then turn it on.
Syntax
Python
and, or, not

and means both conditions must be true.

or means at least one condition is true.

not reverses the condition.

Examples
This checks if both a and b are true. Result will be False because b is False.
Python
a = True
b = False
result = a and b
This checks if either a or b is true. Result will be True because a is True.
Python
a = True
b = False
result = a or b
This reverses a. Since a is True, result will be False.
Python
a = True
result = not a
Sample Program

This program checks if it is raining and if you have an umbrella. It tells you what to do based on these conditions.

Python
is_raining = True
have_umbrella = False

if is_raining and not have_umbrella:
    print("Take a raincoat!")
elif is_raining and have_umbrella:
    print("You are ready for rain.")
else:
    print("Enjoy your day!")
OutputSuccess
Important Notes

Logical operators always return True or False.

Use parentheses to group conditions for clarity, like (a and b) or (c and not d).

Summary

Logical operators combine true/false values to help make decisions.

Use and when all conditions must be true.

Use or when any condition can be true.

Use not to reverse a condition.