Python Operators

🐍 Python Operators

Operators in Python are used to perform operations on variables and values.

Python has 7 types of operators:

  1. Arithmetic Operators

  2. Assignment Operators

  3. Comparison (Relational) Operators

  4. Logical Operators

  5. Identity Operators

  6. Membership Operators

  7. Bitwise Operators


1️⃣ Arithmetic Operators

Used for mathematical calculations.

OperatorMeaningExample
+Addition10 + 5 → 15
-Subtraction10 - 5 → 5
*Multiplication10 * 5 → 50
/Division10 / 5 → 2.0
%Modulus (remainder)10 % 3 → 1
//Floor Division10 // 3 → 3
**Power2 ** 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)

2️⃣ Assignment Operators

Used to assign and update variables.

OperatorMeaningExample
=Assign valuex = 10
+=Add and assignx += 5 → x = x + 5
-=Subtract and assignx -= 5
*=Multiply and assignx *= 5
/=Divide and assignx /= 5
//=, %=, **=Other combinations

Example:

x = 10
x += 5
print(x) # 15

3️⃣ Comparison Operators

Used to compare values — result is True or False.

OperatorMeaningExample
==Equal to5 == 5 → True
!=Not equal5 != 2 → True
>Greater than5 > 2 → True
<Less than5 < 2 → False
>=Greater or equal5 >= 5 → True
<=Less or equal3 <= 5 → True

Example:

print(10 == 10)
print(10 < 5)
print(10 >= 9)

4️⃣ Logical Operators

Used to combine conditions.

OperatorMeaning
andTrue if both are True
orTrue if at least one is True
notReverses True ↔ False

Example:

a = 10
b = 5
print(a > 5 and b < 2) # False
print(a > 5 or b < 2) # True
print(not(a > 5)) # False

5️⃣ Identity Operators

Used to compare memory locations, not values.

OperatorMeaning
isTrue if objects are same memory reference
is notFalse if objects are same

Example:

x = [1,2,3]
y = [1,2,3]
z = x
print(x is z) # True
print(x is y) # False
print(x == y) # True (values equal)

6️⃣ Membership Operators

Used to check if a value exists in sequence (string, list, tuple, etc.)

OperatorMeaning
inTrue if value exists
not inTrue if does NOT exist

Example:

text = "Python"
print("Py" in text) # True
print("Java" not in text) # True

7️⃣ Bitwise Operators (Advanced)

Works on bits (0,1).

OperatorMeaningExample
&AND5 & 3 → 1
``OR
^XOR5 ^ 3 → 6
~NOT~5 → -6
<<Left shift2 << 1 → 4
>>Right shift4 >> 1 → 2

Example:

print(5 & 3)
print(5 | 3)
print(5 ^ 3)
print(2 << 1)
print(4 >> 1)

🎯 Operator Precedence (Order of Execution)

Like math rules (BODMAS):

Highest → Lowest:

1. () Parentheses
2. ** Exponent
3. *, /, //, %
4. +, -
5. Comparison
6. not
7. and
8. or

Example:

x = 10 + 3 * 2 ** 2
print(x) # 22

⭐ Mini Real Example


 

You may also like...