0
0
Pythonprogramming~5 mins

Logical operators in conditions in Python

Choose your learning style9 modes available
Introduction
Logical operators help us combine multiple true or false checks to make decisions in our programs.
When you want to check if two things are both true before doing something.
When you want to do something if at least one of many conditions is true.
When you want to do something only if a condition is not true.
When you want to make your program smarter by checking several rules at once.
Syntax
Python
if condition1 and condition2:
    # do something

if condition1 or condition2:
    # do something

if not condition:
    # do something
Use and to require all conditions to be true.
Use or to require at least one condition to be true.
Use not to reverse the truth of a condition.
Examples
Checks if age is between 18 and 30, both conditions must be true.
Python
age = 20
if age >= 18 and age <= 30:
    print("You are a young adult.")
Checks if the day is Saturday or Sunday, only one condition needs to be true.
Python
day = "Saturday"
if day == "Saturday" or day == "Sunday":
    print("It's the weekend!")
Checks if it is not raining.
Python
is_raining = False
if not is_raining:
    print("You don't need an umbrella.")
Sample Program
This program checks if the temperature is above 20 and it is sunny to suggest going for a walk. It also checks if it's cold or not sunny to suggest staying inside.
Python
temperature = 25
is_sunny = True

if temperature > 20 and is_sunny:
    print("It's a nice day for a walk.")

if temperature < 10 or not is_sunny:
    print("Better stay inside.")
OutputSuccess
Important Notes
Remember that and needs all conditions true to pass.
With or, only one condition needs to be true.
Use parentheses to group conditions if you have many combined.
Summary
Logical operators help combine multiple true/false checks.
and means all conditions must be true.
or means at least one condition must be true.
not reverses the condition's truth.