Chapter 2 of 14

Python Operators

Master arithmetic, comparison, logical, assignment, bitwise, membership, and identity operators with practical examples.

Meritshot14 min read
PythonOperatorsArithmeticLogic
All Python Chapters

What Are Operators?

Operators are special symbols or keywords that perform operations on values (called operands). For example, in 5 + 3, the + is the operator and 5 and 3 are operands. Python supports seven categories of operators.

Arithmetic Operators

Used for mathematical calculations.

OperatorNameExampleResult
+Addition5 + 38
-Subtraction10 - 46
*Multiplication3 * 721
/Division (float)15 / 43.75
//Floor Division15 // 43
%Modulus (remainder)15 % 43
**Exponentiation2 ** 38
a = 10
b = 3

print(a + b)    # 13    — addition
print(a - b)    # 7     — subtraction
print(a * b)    # 30    — multiplication
print(a / b)    # 3.333 — always returns float
print(a // b)   # 3     — rounds DOWN to nearest int
print(a % b)    # 1     — remainder after division
print(a ** b)   # 1000  — 10 to the power of 3

Division: / vs //

This distinction trips up many beginners:

# / always returns a float
print(10 / 2)     # 5.0 (not 5)
print(7 / 2)      # 3.5

# // always rounds DOWN (floor division)
print(7 // 2)     # 3
print(-7 // 2)    # -4 (rounds DOWN, not towards zero!)
print(7.0 // 2)   # 3.0 (returns float if either operand is float)

Modulus Operator %

Returns the remainder of division. Extremely useful in programming:

# Check if a number is even or odd
num = 17
if num % 2 == 0:
    print("Even")
else:
    print("Odd")  # This runs

# Check divisibility
print(15 % 5 == 0)  # True — 15 is divisible by 5
print(15 % 4 == 0)  # False

# Extract last digit of a number
number = 12345
last_digit = number % 10
print(last_digit)  # 5

# Cycle through values (useful for circular indices)
for i in range(10):
    day = i % 7  # cycles through 0-6
    print(f"Step {i}: Day {day}")

# Convert total seconds to minutes and seconds
total_seconds = 185
minutes = total_seconds // 60   # 3
seconds = total_seconds % 60    # 5
print(f"{minutes}m {seconds}s")  # 3m 5s

Exponentiation

print(2 ** 10)       # 1024
print(9 ** 0.5)      # 3.0 (square root!)
print(27 ** (1/3))   # 3.0 (cube root)

# Python handles large numbers natively
print(2 ** 100)  # 1267650600228229401496703205376

Operator Precedence (Order of Operations)

Python follows standard mathematical precedence (PEMDAS/BODMAS):

PriorityOperatorDescription
1 (highest)**Exponentiation
2+x, -xUnary plus/minus
3*, /, //, %Multiply, divide, modulus
4 (lowest)+, -Add, subtract
# Without parentheses
print(2 + 3 * 4)      # 14 (not 20) — multiplication first
print(2 ** 3 ** 2)     # 512 — right-to-left: 3**2=9, then 2**9=512

# With parentheses (always use them for clarity)
print((2 + 3) * 4)    # 20
print((2 ** 3) ** 2)   # 64

Best practice: When in doubt, use parentheses to make your intent clear. Code readability matters more than saving a few characters.

Comparison Operators

Comparison operators compare two values and return a boolean (True or False).

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than7 > 3True
<Less than2 < 8True
>=Greater or equal5 >= 5True
<=Less or equal3 <= 1False
x = 10
y = 20

print(x == y)    # False
print(x != y)    # True
print(x > y)     # False
print(x < y)     # True
print(x >= 10)   # True
print(x <= 5)    # False

Chained Comparisons (Pythonic!)

Python allows chaining comparisons — a feature most languages don't have:

age = 25

# Instead of: age >= 18 and age <= 65
print(18 <= age <= 65)   # True

# Chain as many as you want
x = 5
print(1 < x < 10)        # True
print(1 < x < 3)         # False
print(0 <= x <= 5 <= 10) # True

Comparing Strings

Strings are compared lexicographically (dictionary order) using Unicode values:

print("apple" < "banana")    # True (a comes before b)
print("abc" < "abd")         # True (c comes before d)
print("Apple" < "apple")     # True (uppercase A=65 < lowercase a=97)
print("hello" == "hello")    # True
print("hello" == "Hello")    # False (case-sensitive)

Comparing Different Types

print(1 == 1.0)    # True — Python compares values, not types
print(1 == True)    # True — True is equivalent to 1
print(0 == False)   # True — False is equivalent to 0
print("1" == 1)     # False — string vs int

Logical Operators

Combine or modify boolean expressions.

OperatorDescriptionExampleResult
andTrue if BOTH are TrueTrue and FalseFalse
orTrue if AT LEAST ONE is TrueTrue or FalseTrue
notReverses the booleannot TrueFalse

Truth Tables

and — both must be True:

ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

or — at least one must be True:

ABA or B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse
age = 25
has_license = True
has_insurance = False

# and — both conditions must be true
if age >= 18 and has_license:
    print("You can drive!")  # ✓

# or — at least one must be true
if has_license or has_insurance:
    print("At least one document present")  # ✓

# not — reverses the condition
if not has_insurance:
    print("Insurance needed!")  # ✓

# Combining multiple operators
if age >= 18 and has_license and not has_insurance:
    print("Can drive but needs insurance")  # ✓

Short-Circuit Evaluation

Python stops evaluating as soon as the result is determined:

# With 'and': if first is False, second is never evaluated
x = 0
result = x != 0 and 10 / x > 2  # Safe! 10/x never runs

# With 'or': if first is True, second is never evaluated
name = "" or "Anonymous"
print(name)  # "Anonymous"

# Practical use: default values
user_input = ""
display_name = user_input or "Guest"
print(display_name)  # "Guest"

Logical Operators with Non-Boolean Values

In Python, and and or don't always return True/False — they return the value that determined the result:

# 'and' returns the first falsy value, or the last value if all truthy
print(0 and 5)         # 0 (first falsy)
print(3 and 5)         # 5 (all truthy, returns last)
print("" and "hello")  # "" (first falsy)

# 'or' returns the first truthy value, or the last value if all falsy
print(0 or 5)          # 5 (first truthy)
print(3 or 5)          # 3 (first truthy)
print("" or "default") # "default"
print(0 or "" or None)  # None (all falsy, returns last)

Assignment Operators

Combine an operation with assignment for cleaner code.

OperatorEquivalent ToExample
=Assignx = 5
+=x = x + valx += 3x = x + 3
-=x = x - valx -= 2x = x - 2
*=x = x * valx *= 4x = x * 4
/=x = x / valx /= 2x = x / 2
//=x = x // valx //= 3x = x // 3
%=x = x % valx %= 3x = x % 3
**=x = x ** valx **= 2x = x ** 2
score = 100
print(score)     # 100

score += 10      # Add 10
print(score)     # 110

score -= 20      # Subtract 20
print(score)     # 90

score *= 2       # Double
print(score)     # 180

score //= 3      # Floor divide by 3
print(score)     # 60

# Works with strings too
greeting = "Hello"
greeting += " World"
print(greeting)  # Hello World

# Works with lists
items = [1, 2]
items += [3, 4]
print(items)     # [1, 2, 3, 4]

Membership Operators

Test whether a value exists in a sequence (string, list, tuple, set, dict).

OperatorDescriptionExample
inTrue if value is found"a" in "apple"True
not inTrue if value is NOT found"z" not in "apple"True
# Strings
print("P" in "Python")         # True
print("java" not in "Python")  # True

# Lists
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)      # True
print("grape" not in fruits)   # True

# Tuples
coords = (10, 20, 30)
print(20 in coords)            # True

# Sets (fastest membership check — O(1))
valid_ids = {101, 102, 103, 104}
print(103 in valid_ids)        # True

# Dictionaries (checks keys, not values)
config = {"host": "localhost", "port": 8080}
print("host" in config)        # True
print("localhost" in config)   # False (that's a value, not a key)
print(8080 in config.values()) # True (check values explicitly)

Practical Example: Input Validation

valid_commands = {"start", "stop", "pause", "resume"}
user_input = input("Enter command: ").lower()

if user_input in valid_commands:
    print(f"Executing: {user_input}")
else:
    print(f"Unknown command: '{user_input}'")
    print(f"Valid commands: {', '.join(valid_commands)}")

Identity Operators

Test whether two variables refer to the same object in memory (not just equal values).

OperatorDescriptionExample
isTrue if same objecta is b
is notTrue if different objectsa is not b
# is vs ==
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)    # True — same value
print(a is b)    # False — different objects in memory
print(a is c)    # True — c points to the same list as a

# Most common use: checking for None
result = None

# Correct — use 'is' for None
if result is None:
    print("No result")

# Also works
if result is not None:
    print("Has result")

Important: Always use is / is not when comparing with None, True, or False. Use == / != for comparing values.

Why is and == Differ

# Small integers are cached (-5 to 256)
a = 256
b = 256
print(a is b)  # True — Python caches small integers

a = 257
b = 257
print(a is b)  # False — different objects (usually)

# Strings may be interned
x = "hello"
y = "hello"
print(x is y)  # True (Python interns short strings)

x = "hello world!"
y = "hello world!"
print(x is y)  # May be False (not guaranteed)

Bitwise Operators

Operate on numbers at the binary (bit) level. Used in low-level programming, flags, permissions, and algorithms.

OperatorNameExampleResult
&AND5 & 31
|OR5 | 37
^XOR5 ^ 36
~NOT~5-6
<<Left shift5 << 110
>>Right shift5 >> 12
# 5 in binary:  101
# 3 in binary:  011

print(5 & 3)    # 1   (001) — AND: both bits must be 1
print(5 | 3)    # 7   (111) — OR: at least one bit is 1
print(5 ^ 3)    # 6   (110) — XOR: exactly one bit is 1
print(~5)       # -6  — inverts all bits
print(5 << 1)   # 10  (1010) — shift left = multiply by 2
print(5 >> 1)   # 2   (10)   — shift right = divide by 2

# Practical: check if number is even (last bit is 0)
num = 42
if num & 1 == 0:
    print(f"{num} is even")

# Practical: permission flags
READ = 0b100     # 4
WRITE = 0b010    # 2
EXECUTE = 0b001  # 1

user_perms = READ | WRITE     # 6 (110) — has read and write
print(user_perms & READ)       # 4 (non-zero = True) — has read?
print(user_perms & EXECUTE)    # 0 (zero = False) — has execute?

Practical Examples

Grade Calculator

marks = float(input("Enter your marks (out of 100): "))

if marks < 0 or marks > 100:
    print("Invalid marks!")
elif marks >= 90:
    print(f"Grade: A+ (Excellent!) — {marks}/100")
elif marks >= 80:
    print(f"Grade: A (Very Good) — {marks}/100")
elif marks >= 70:
    print(f"Grade: B (Good) — {marks}/100")
elif marks >= 60:
    print(f"Grade: C (Average) — {marks}/100")
elif marks >= 50:
    print(f"Grade: D (Below Average) — {marks}/100")
else:
    print(f"Grade: F (Fail) — {marks}/100")

Leap Year Checker

year = int(input("Enter a year: "))

# A year is a leap year if:
# - Divisible by 4 AND not by 100, OR
# - Divisible by 400
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

if is_leap:
    print(f"{year} is a leap year")
else:
    print(f"{year} is not a leap year")

Electricity Bill Calculator

units = float(input("Enter units consumed: "))

if units <= 100:
    bill = units * 5
elif units <= 200:
    bill = (100 * 5) + ((units - 100) * 7)
elif units <= 300:
    bill = (100 * 5) + (100 * 7) + ((units - 200) * 10)
else:
    bill = (100 * 5) + (100 * 7) + (100 * 10) + ((units - 300) * 15)

surcharge = bill * 0.05  # 5% surcharge
total = bill + surcharge

print(f"\nUnits consumed: {units}")
print(f"Base bill:     ₹{bill:,.2f}")
print(f"Surcharge (5%): ₹{surcharge:,.2f}")
print(f"Total bill:    ₹{total:,.2f}")

Practice Exercises

  1. Write a program that checks if a number is positive, negative, or zero
  2. Check if a given year is a century year (divisible by 100)
  3. Write a program that takes three numbers and prints the largest
  4. Calculate compound interest: A = P * (1 + r/n)^(n*t)
  5. Write a program that checks if a number is divisible by both 3 and 5
  6. Create a program that converts a decimal number to binary using // and %

Summary

In this chapter, you learned:

  • Arithmetic operators+, -, *, /, //, %, ** with their nuances
  • Comparison operators==, !=, >, <, >=, <= and chained comparisons
  • Logical operatorsand, or, not with truth tables and short-circuit evaluation
  • Assignment operators+=, -=, *=, /= and friends
  • Membership operatorsin, not in for checking sequences
  • Identity operatorsis, is not for object identity (use with None)
  • Bitwise operators&, |, ^, ~, <<, >> for bit-level operations
  • Operator precedence — PEMDAS rules and when to use parentheses
  • Practical programs: grade calculator, leap year checker, electricity bill

Next up: Data Types — deep dive into strings, numbers, booleans, and type conversion.