๐ฏ Lesson Objective
To understand different types of operators in Python and how to use them in expressions to perform calculations or logic.
๐ง 1. What Are Operators?
Operators are special symbols that perform operations on variables and values.
Expressions are combinations of variables, operators, and values that produce a result.
Example:
x = 10
y = 5
result = x + y
print(result) # Output: 15
โ๏ธ 2. Types of Operators
A. Arithmetic Operators
Used for mathematical operations.
| Operator | Description | Example | Output |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 5 - 3 | 2 |
* | Multiplication | 5 * 3 | 15 |
/ | Division | 10 / 3 | 3.3333 |
// | Floor Division | 10 // 3 | 3 |
% | Modulus (Remainder) | 10 % 3 | 1 |
** | Exponentiation | 2 ** 3 | 8 |
Example:
a, b = 10, 3
print(a + b, a - b, a * b, a / b, a // b, a % b, a ** b)
B. Comparison Operators
Used to compare two values. They return either True or False.
| Operator | Meaning | Example | Output |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 7 > 4 | True |
< | Less than | 3 < 5 | True |
>= | Greater or equal | 5 >= 5 | True |
<= | Less or equal | 4 <= 3 | False |
Example:
x, y = 10, 20
print(x > y) # False
print(x != y) # True
C. Logical Operators
Used to combine conditional statements.
| Operator | Description | Example | Output |
|---|---|---|---|
and | True if both are true | x > 5 and y < 30 | True |
or | True if one is true | x > 15 or y < 30 | True |
not | Reverses the result | not(x > 5) | False |
Example:
x, y = 10, 20
print(x > 5 and y < 25) # True
print(x > 15 or y < 25) # True
print(not(x > 5)) # False
D. Assignment Operators
Used to assign values to variables.
| Operator | Example | Equivalent To |
|---|---|---|
= | x = 10 | x = 10 |
+= | x += 2 | x = x + 2 |
-= | x -= 3 | x = x - 3 |
*= | x *= 2 | x = x * 2 |
/= | x /= 2 | x = x / 2 |
Example:
x = 5
x += 3
print(x) # Output: 8
E. Bitwise Operators (Advanced)
Used to perform operations on binary numbers.
| Operator | Description | Example | Output |
|---|---|---|---|
& | AND | 5 & 3 | 1 |
| ` | ` | OR | `5 |
^ | XOR | 5 ^ 3 | 6 |
~ | NOT | ~5 | -6 |
<< | Left shift | 5 << 1 | 10 |
>> | Right shift | 5 >> 1 | 2 |
Example:
a, b = 5, 3
print(a & b, a | b, a ^ b)
๐งฉ 3. Expressions
An expression is a combination of values, variables, and operators that evaluates to a result.
Example:
x = 10
y = 5
z = (x + y) * 2
print(z) # Output: 30
๐ง 4. Practice Ideas
- Write a Python program to calculate the area of a rectangle using variables.
- Check if a number is positive and even using comparison and logical operators.
- Create a program that swaps two variables using assignment operators.

Leave a Reply