Floor division is useful for integer calculations like dividing items into groups.
Modulus helps check if a number is even/odd (n % 2 == 0 means even) or for wrapping values.
Comparison Operators
These compare values and return True or False:
Operator
Name
Example
Result
==
Equal to
5 == 5
True
!=
Not equal to
5 != 3
True
>
Greater than
7 > 3
True
<
Less than
2 < 8
True
>=
Greater than or equal
5 >= 5
True
<=
Less than or equal
4 <= 3
False
Common Mistake
Don’t confuse = (assignment) with == (comparison)!
age =25# Instead of: age >= 18 and age <= 65# You can write:print(18<= age <=65) # True# This also worksx =5print(1< x <10) # Trueprint(1< x <3) # False
Logical Operators
Combine multiple conditions:
Operator
Description
Example
Result
and
Both must be True
True and False
False
or
At least one True
True or False
True
not
Inverts the value
not True
False
Truth Tables
flowchart TB
subgraph AND["and"]
A1["True and True"] --> B1["True"]
A2["True and False"] --> B2["False"]
A3["False and True"] --> B3["False"]
A4["False and False"] --> B4["False"]
end
subgraph OR["or"]
C1["True or True"] --> D1["True"]
C2["True or False"] --> D2["True"]
C3["False or True"] --> D3["True"]
C4["False or False"] --> D4["False"]
end
Practical Examples
logical.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
age =25has_license =Trueis_insured =False# AND: Both conditions must be truecan_drive = age >=18and has_license
print(f"Can drive: {can_drive}") # True# OR: At least one condition must be truecan_rent_car = age >=25or has_license
print(f"Can rent car: {can_rent_car}") # True# NOT: Inverts the conditionneeds_insurance =not is_insured
print(f"Needs insurance: {needs_insurance}") # True# Complex conditionscan_work = age >=18and (has_license or is_insured)
print(f"Can work: {can_work}") # True
Short-Circuit Evaluation
Python is smart! With and, if the first condition is False, it doesn’t check the second. With or, if the first is True, it doesn’t check the second.
# Without parenthesesresult =2+3*4print(result) # 14 (not 20!)# Python does: 2 + (3 * 4) = 2 + 12 = 14# With parentheses to change orderresult = (2+3) *4print(result) # 20# Complex expressionx =10y =5z =2result = x + y * z **2# x + (y * (z ** 2))print(result) # 10 + (5 * 4) = 10 + 20 = 30# Boolean precedencea =Trueb =Falsec =Trueresult = a or b and c # a or (b and c)print(result) # True (because 'and' before 'or')
When in Doubt, Use Parentheses!
Parentheses make your code clearer and ensure the order you want. (a + b) * c is easier to understand than relying on precedence rules.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!