๐ 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: