Operators and Expressions
Operators and Expressions
Operators let you perform operations on values and variables.
Arithmetic Operators
| Operator | Description | Example |
|---|---|---|
+ |
Addition | 5 + 3 → 8 |
- |
Subtraction | 5 - 3 → 2 |
* |
Multiplication | 5 * 3 → 15 |
/ |
Division | 5 / 3 → 1.666... |
// |
Floor Division | 5 // 3 → 1 |
% |
Modulo (remainder) | 5 % 3 → 2 |
** |
Exponentiation | 5 ** 3 → 125 |
a = 10
b = 3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.333...
print(a // b) # 3
print(a % b) # 1
print(a ** b) # 1000
Comparison Operators
These return True or False:
| Operator | Description | Example |
|---|---|---|
== |
Equal to | 5 == 5 → True |
!= |
Not equal to | 5 != 3 → True |
> |
Greater than | 5 > 3 → True |
< |
Less than | 5 < 3 → False |
>= |
Greater or equal | 5 >= 5 → True |
<= |
Less or equal | 5 <= 3 → False |
x = 10
y = 5
print(x == y) # False
print(x != y) # True
print(x > y) # True
print(x < y) # False
Logical Operators
Combine boolean expressions:
| Operator | Description | Example |
|---|---|---|
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 |
age = 25
has_license = True
# Can they rent a car?
can_rent = age >= 21 and has_license
print(can_rent) # True
# Is it a weekend?
is_saturday = True
is_sunday = False
is_weekend = is_saturday or is_sunday
print(is_weekend) # True
String Operators
# Concatenation
first = "Hello"
last = "World"
full = first + " " + last
print(full) # "Hello World"
# Repetition
line = "-" * 20
print(line) # "--------------------"
Order of Operations
Python follows standard math precedence (PEMDAS):
- Parentheses
() - Exponents
** - Multiplication/Division
* / // % - Addition/Subtraction
+ -
result = 2 + 3 * 4 # 14 (not 20!)
result = (2 + 3) * 4 # 20 (parentheses first)
Tip: When in doubt, use parentheses to make your intentions clear!