Skip to main content

Python Operators

Operators are the symbols that drive the logic of any programming language. They act as the engine for calculations, data manipulation, and decision-making.

1. Arithmetic Operators - Math​

These operators perform standard mathematical calculations.

SymbolNameDescriptionExampleResult+AdditionAdds two operands.5 + 38-SubtractionSubtracts the right operand from the left.10 - 28*MultiplicationMultiplies two operands.4 * 28/DivisionAlways returns a Float (decimal).10 / 25.0//Floor DivisionDivision that rounds down to the nearest whole number.10 // 33%ModulusReturns the Remainder of the division.10 % 31**ExponentiationRaises the left operand to the power of the right ($x^y$).2 ** 38

**The Power of Modulus **%​

The modulus operator is essential for logic, not just math.

  • Even/Odd Check: If number % 2 == 0, the number is Even.

  • Cyclic Indexing: If you want to loop through a list of 5 items continuously, use index % 5. The result cycles through 0, 1, 2, 3, 4, then resets to 0 automatically.


2. Assignment Operators​

Used to assign and update values in variables.

OperatorLogicEquivalent To=Assignx = 5+=Add & Assignx = x + 3-=Subtract & Assignx = x - 3*=Multiply & Assignx = x * 3/=Divide & Assignx = x / 3%=Modulus & Assignx = x % 3

The Walrus Operator :=​

A special operator that allows you to assign a value to a variable inside an expression (like an if statement).

# Instead of 2 lines:
# n = len(text)
# if n > 10: ...

# Do it in 1 line:
if (n := len(text)) > 10:
print(f"Too long: {n} chars")

3. Comparison Operators​

Used to compare two values. They always return a Boolean (True or False).

SymbolNameLogic==EqualTrue if values are identical.!=Not EqualTrue if values are different.>Greater Than5 > 3 is True.=Greater or Equal5 >= 5 is True.<=Less or Equal4 <= 5 is True.

Chained Comparisons​

Python allows math-like chaining, which is cleaner than using multiple and statements.

x = 10
# Clean Pythonic way
if 5 < x < 20:
print("x is between 5 and 20")

4. Logical Operators​

Used to combine conditional statements. These follow Boolean logic.

OperatorDescriptionLogic RuleandReturns True if BOTH statements are true.T + T = TorReturns True if AT LEAST ONE statement is true.T + F = TnotReverses the result.True → False

Short-Circuit Evaluation​

Python evaluates logic lazily to save resources.

  • and** Short-Circuit:** If the first condition is False, Python stops immediately (result is definitely False).

  • or** Short-Circuit:** If the first condition is True, Python stops immediately (result is definitely True).

Real World Use: Preventing crashes.

# Safe Code
# Python checks 'len > 0' first. If False, it never runs index&#91;0], preventing a crash.
if len(my_list) > 0 and my_list&#91;0] == "Admin":
print("Welcome Admin")

**5. Identity Operators **is​

Used to compare Objects (Memory), not just Values (Data).

Operator****DescriptionisTrue if both variables point to the same object in memory.is notTrue if they point to different objects.

**The Trap: is vs **==​

  • == checks Content: "Do these variables hold the same data?"

  • is checks Address: "Do these variables point to the exact same memory slot?"

list1 = &#91;1, 2, 3]
list2 = &#91;1, 2, 3] # A copy

print(list1 == list2) # True (Data is same)
print(list1 is list2) # False (They are two different lists in memory)

**6. Membership Operators **in​

Used to test if a sequence (List, String, Tuple, Dict) contains a specific value.

OperatorDescriptionExampleinTrue if value is found."a" in "apple"not inTrue if value is NOT found."x" not in "apple"


7. Bitwise Operators​

Used to manipulate data at the binary level (bits). Critical for permissions, encryption, and low-level optimization.

OperatorNameExample (x=5 (0101), y=3 (0011))Result&ANDx & y (Both bits must be 1)0001 (1)``OR`x^XORx ^ y (Only one bit is 1)0110 (6)~NOT~x (Invert all bits)-(x+1)<<Left Shiftx << 1 (Push zeros from right)1010 (10)>>Right Shiftx >> 1 (Push bits off right)0010 (2)


8. Operator Precedence​

When multiple operators appear in one line, Python follows a strict hierarchy.

PriorityOperatorDescription1 (Highest)( )Parentheses (Grouping)2Exponentiation (Power)3+x, -x, ~xUnary Plus, Unary Minus, Bitwise NOT****4*, /, //, %Multiplication, Division, Floor Division, Modulus5****+, -Addition, Subtraction6****<<, >>Bitwise Shifts (Left/Right)7&Bitwise AND8^Bitwise XOR9********10==, !=, >, >=, <, <=, is, is not, in, not inComparisons, Identity, Membership11notLogical NOT12andLogical AND13 (Lowest)orLogical OR**

9. Operator Overloading - Magic Methods​

You can change how operators behave for your own custom classes. For example, if you create a Wallet class, you can teach Python how to add two wallets together using +.

You define special methods (Double Underscore or "Dunder" methods):

  • add handles +

  • sub handles -

  • eq handles ==

class Wallet:
def __init__(self, money):
self.money = money

# Teach Python what to do when we use '+' on Wallets
def __add__(self, other):
return Wallet(self.money + other.money)

w1 = Wallet(50)
w2 = Wallet(100)
w3 = w1 + w2 # Python calls w1.__add__(w2)

print(w3.money) # Output: 150

​