§2.2 Operators and Expressions
KM
bykarutt
2025-06-03
Operators and Expressions
In programming, you use "operators" to perform calculations, comparisons, and make decisions. Here are the main types and how to use them.
Arithmetic Operators (Calculations)
- What You Can Do: Perform addition (
+), subtraction (-), multiplication (*), division (/), and more.
a = 5
b = 3
print(a + b) # 8
print(a - b) # 2
print(a * b) # 15
print(a / b) # 1.666...Comparison Operators (Comparing Values)
- What You Can Do: Compare two values and get
TrueorFalseas a result. Used in "conditionals" you'll learn next.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to (is also works) | 5 == 1 | False |
!= | Not equal to (is not also) | 5 != 3 | True |
> | Greater than | 1 > 4 | False |
< | Less than | 2 < 8 | True |
>= | Greater than or equal to | 5 >= 5 | True |
<= | Less than or equal to | 3 <= 5 | True |
The result of a comparison operator is always a Boolean value: True or False.
x = 5
y = 5
print(x == y) # True
print(x != y) # False
print(x > 3) # True
print(x < 10) # TrueLogical Operators (Combining Conditions)
- What You Can Do: Use "and," "or," and "not" to combine or reverse conditions.
| Operator | Meaning | Example | Result |
|---|---|---|---|
and | Both are True | True and False | False |
or | Either is True | True or False | True |
not | Reverse | not False | True |
flag1 = True
flag2 = False
print(flag1 and flag2) # False
print(flag1 or flag2) # True
print(not flag2) # True# Example combining with comparison operators
age = 12
is_student = False
print(age <= 18 or is_student) # True
print(10 < age and age < 30) # TrueAssignment Operators (Storing/Updating Values)
- What You Can Do: Assign values to variables or update them with calculations.
| Operator | Meaning | Example | Same as |
|---|---|---|---|
= | Assign value | x = 5 | — |
+= | Add and assign | x += 2 | x = x + 2 |
-= | Subtract and assign | x -= 1 | x = x - 1 |
*= | Multiply and assign | x *= 3 | x = x * 3 |
/= | Divide and assign | x /= 2 | x = x / 2 |
x = 4 # Assign 4 to x
y = x + 5 # Assign x + 5 to y
x += 2 # Add 2 to x (x = x + 2)
print(x) # 6
print(y) # 9count = 0