Lesson 2.3: Operators (Arithmetic, Comparison, Logical, Assignment)
Introduction:
Operators in Python are special symbols used to perform operations on variables and values. Understanding operators is essential for performing calculations, comparisons, and logical operations in your programs.
1. Arithmetic Operators:
Used for mathematical calculations.
| Operator | Description | Example | Output |
|---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 5 - 3 |
2 |
* |
Multiplication | 5 * 3 |
15 |
/ |
Division | 5 / 2 |
2.5 |
// |
Floor Division | 5 // 2 |
2 |
% |
Modulus (Remainder) | 5 % 2 |
1 |
** |
Exponentiation | 5 ** 2 |
25 |
2. Comparison Operators:
Used to compare two values and return True or False.
| Operator | Description | Example | Output |
|---|---|---|---|
== |
Equal to | 5 == 5 |
True |
!= |
Not equal to | 5 != 3 |
True |
> |
Greater than | 5 > 3 |
True |
< |
Less than | 5 < 3 |
False |
>= |
Greater than or equal | 5 >= 5 |
True |
<= |
Less than or equal | 5 <= 3 |
False |
3. Logical Operators:
Used to combine conditional statements.
| Operator | Description | Example | Output |
|---|---|---|---|
and |
True if both are True | True and False |
False |
or |
True if any is True | True or False |
True |
not |
Reverse the boolean value | not True |
False |
4. Assignment Operators:
Used to assign values to variables.
| Operator | Description | Example |
|---|---|---|
= |
Assign | x = 5 |
+= |
Add and assign | x += 3 → x = x + 3 |
-= |
Subtract and assign | x -= 2 → x = x – 2 |
*= |
Multiply and assign | x *= 2 → x = x * 2 |
/= |
Divide and assign | x /= 2 → x = x / 2 |
%= |
Modulus and assign | x %= 3 → x = x % 3 |
Practical Tip:
-
Combine different operators to create complex expressions.
-
Use parentheses
()to control the order of operations.
Example:
Learning Outcome of This Lesson:
-
Understand arithmetic, comparison, logical, and assignment operators
-
Apply operators to perform calculations and comparisons
-
Combine operators in expressions for complex operations
-
Write programs using operators effectively
