Table of Contents
Logical operators
Logical operators let you combine and invert conditions. They are used inside if, elif, and while statements to build more complex decisions.
Python has three main logical operators:
andornot
They work with expressions that are either True or False (Boolean values).
`and`: all conditions must be True
and combines two (or more) conditions and is True only if all parts are True.
General idea:
$$
A \text{ and } B \text{ is True only if both } A \text{ and } B \text{ are True.}
$$
In Python:
age = 20
has_ticket = True
if age >= 18 and has_ticket:
print("You can enter.")
else:
print("You cannot enter.")Here:
age >= 18isTruehas_ticketisTrueTrue and TrueisTrue, so"You can enter."is printed.
Truth table for and:
True and True→TrueTrue and False→FalseFalse and True→FalseFalse and False→False
`or`: at least one condition must be True
or combines conditions and is True if at least one part is True.
General idea:
$$
A \text{ or } B \text{ is False only if both } A \text{ and } B \text{ are False.}
$$
Example:
is_admin = False
is_moderator = True
if is_admin or is_moderator:
print("You have special access.")
else:
print("Normal user access.")Here:
is_adminisFalseis_moderatorisTrueFalse or TrueisTrue, so"You have special access."is printed.
Truth table for or:
True or True→TrueTrue or False→TrueFalse or True→TrueFalse or False→False
`not`: reverse a condition
not flips True to False and False to True.
General idea:
$$
\text{not } A \text{ is True if and only if } A \text{ is False.}
$$
Example:
logged_in = False
if not logged_in:
print("Please log in first.")logged_inisFalsenot logged_inisTrue- The message is printed.
Truth table for not:
not True→Falsenot False→True
Combining multiple logical operators
You can use and, or, and not together to build more detailed conditions.
Example:
age = 16
has_permission = True
if (age >= 18 or has_permission) and not (age < 10):
print("Allowed.")
else:
print("Not allowed.")Read step by step:
age >= 18→Falsehas_permission→Trueage >= 18 or has_permission→False or True→Trueage < 10→Falsenot (age < 10)→not False→True- Final:
True and True→True→"Allowed."
Operator precedence and parentheses
When you combine multiple logical operators, Python does not always evaluate them from left to right. There is an order (precedence):
notandor
For example:
result = True or False and False
print(result)This is evaluated as:
False and False→FalseTrue or False→True
So result is True.
If you want a different order, use parentheses:
result = (True or False) and False
print(result) # This is FalseParentheses make your code clearer and safer, especially for beginners.
Common patterns with logical operators
Checking a range with `and`
A common use is to check that a value is between two numbers:
temperature = 22
if temperature >= 18 and temperature <= 25:
print("Comfortable temperature.")Python also allows this shorter form (just to recognize it when you see it):
if 18 <= temperature <= 25:
print("Comfortable temperature.")Multiple allowed values with `or`
Use or when any of several values is acceptable:
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")Typical beginner mistakes with logical operators
1. Using `and` instead of `or` (and vice versa)
Example:
color = "red"
# Wrong if you mean "red OR blue"
if color == "red" and color == "blue":
print("Primary color.")
This condition is always False because color cannot be both "red" and "blue" at the same time.
Correct:
if color == "red" or color == "blue":
print("Primary color.")2. Forgetting to repeat the variable in comparisons
Incorrect:
age = 20
# This does NOT do what it seems
if age == 18 or 20:
print("Age is 18 or 20")
age == 18 or 20 is interpreted as (age == 18) or 20, and 20 is always treated as True in this context, so the condition always passes.
Correct:
if age == 18 or age == 20:
print("Age is 18 or 20")3. Relying on precedence instead of using parentheses
This can make code confusing and lead to bugs:
age = 17
has_permission = True
with_parent = True
# Harder to read and can be misinterpreted
if age >= 18 or has_permission and with_parent:
print("You can enter.")Better with parentheses to show the intended logic:
if age >= 18 or (has_permission and with_parent):
print("You can enter.")Practice ideas
Try writing small if statements using logical operators:
- Ask the user for their age and day of the week, and allow a discount if:
- they are under 18 or
- it is Wednesday.
- Ask for a score, and print
"Pass"only if it is at least 50 and not greater than 100. - Ask if it is raining and if the user has an umbrella; print whether they can go outside based on combinations of
and,or, andnot.