📘 Phase 1: Programming Fundamentals
🐍 Topic 2: Python Operators
In the previous lesson, you learned about Variables & Data Types. Now it's time to learn how Python performs calculations, comparisons, and logical operations using operators.
Operators are one of the most fundamental concepts in Python. You'll use them in almost every program, from simple calculations to complex Machine Learning algorithms.
🔹 1. What are Operators?
Operators are special symbols used to perform operations on variables and values.
Example:
a = 10
b = 5
print(a + b)
Output:
15
Here, "+" is an operator that adds two numbers.
🔹 2. Types of Operators in Python
Python has several types of operators:
✅ Arithmetic Operators
✅ Comparison Operators
✅ Assignment Operators
✅ Logical Operators
✅ Membership Operators
✅ Identity Operators
🔹 3. Arithmetic Operators ⭐
Used for mathematical calculations.
Operators:
• ** + Addition**: 10 + 5 = 15
• - Subtraction: 10 - 5 = 5
• ** Multiplication*: 10 * 5 = 50
• / Division: 10 / 5 = 2.0
• // Floor Division: 10 // 3 = 3
• % Modulus (Remainder): 10 % 3 = 1
• ** Exponent: 2 ** 3 = 8
Example:
a = 10
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
🔹 4. Comparison Operators ⭐
Used to compare two values. The result is always True or False.
Operators:
• == Equal to
• != Not Equal to
• > Greater than
• < Less than
• >= Greater than or Equal to
• <= Less than or Equal to
Example:
x = 20
y = 10
print(x > y)
print(x == y)
print(x != y)
Output:
True
False
True
🔹 5. Assignment Operators
Used to assign values to variables.
x = 10
x += 5
print(x)
Output:
15
Other assignment operators:
x -= 2
x *= 3
x /= 2
🔹 6. Logical Operators ⭐
Used to combine multiple conditions.
and
Returns True only if both conditions are True.
age = 25
print(age > 18 and age < 30)
Output:
True
or
Returns True if at least one condition is True.
print(age < 18 or age < 30)
Output:
True
not
Reverses the result.
print(not(age > 18))
Output:
False
🔹 7. Membership Operators
Used to check whether a value exists in a sequence.
in
fruits = ["Apple", "Banana", "Mango"]
print("Apple" in fruits)
Output:
True
not in
print("Orange" not in fruits)Output:
True
🔹 8. Identity Operators
Used to check whether two variables refer to the same object.
is
a = [1, 2]
b = a
print(a is b)
Output:
True
is not
x = [1, 2]
y = [1, 2]
print(x is not y)
Output:
True
🔹 9. Operator Precedence
Python follows the PEMDAS/BODMAS rule while evaluating expressions.
Example: