Operators: Arithmetic, Comparison, Logical, Bitwise

অপারেটর — গণিত, তুলনা, যুক্তি, বিট

Read: ~28 min Intermediate 5 practice problems Live code runner

1. What Is an Operator?

An operator is a symbol (or keyword) that tells Python to perform a specific operation on one or more values — called operands. Python operators fall into a handful of broad families: arithmetic (math), comparison (equality/ordering), logical (and/or/not), bitwise (bit-level manipulation), assignment, membership (in), and identity (is).

Operator হলো এমন একটি চিহ্ন (বা keyword) যা Python-কে বলে দেয় — এক বা একাধিক মানের (operand) উপর একটি নির্দিষ্ট operation চালাতে। Python-এর অপারেটরগুলো কয়েকটি শ্রেণিতে ভাগ করা যায়: arithmetic, comparison, logical, bitwise, assignment, membership, এবং identity।

2. Arithmetic Operators

OpMeaningExampleResult
+Addition7 + 310
-Subtraction7 - 34
*Multiplication7 * 321
/True division (always float)7 / 23.5
//Floor division7 // 23
%Modulus (remainder)7 % 21
**Exponentiation2 ** 101024
/ vs // — Python 3-এ / সবসময় float দেয় (7 / 2 == 3.5), আর // floor দেয় (7 // 2 == 3)। C/Java-এর integer division-এর মতো চাইলে // ব্যবহার করুন।
arith.py
a, b = 17, 5
print(f"{a} + {b} = {a + b}")
print(f"{a} / {b} = {a / b}")     # float
print(f"{a} // {b} = {a // b}")   # floor
print(f"{a} % {b}  = {a % b}")    # remainder
print(f"{a} ** {b} = {a ** b}")   # power

# Python handles huge integers with no overflow
print(2 ** 100)

3. Comparison Operators & Chaining

Python's comparison operators are standard (==, !=, <, <=, >, >=) — with one beautiful twist you won't find in C or Java: comparison chaining.

Python-এর comparison operator সাধারণ: ==, !=, <, <=, >, >= — কিন্তু একটি বিশেষ বৈশিষ্ট্য রয়েছে যা C/Java-তে নেই: comparison chaining।
compare.py
age = 22

# Traditional way
if age >= 18 and age <= 60:
    print("working age")

# Pythonic way — chained
if 18 <= age <= 60:
    print("working age (chained)")

# Chains can be longer
x = 5
print(0 < x < 10 < 100)

4. Logical Operators: and, or, not

Python uses English words instead of &&, ||, !. They are short-circuit — evaluation stops as soon as the result is known. They also return one of the operands (not always a bool), which enables handy idioms.

logic.py
# Short-circuit
def expensive():
    print("called!")
    return True

# `expensive()` never runs — False short-circuits `and`
print(False and expensive())

# Returns an operand, not a bool
name = ""
display = name or "Anonymous"
print(display)   # Anonymous

# Truthiness: [], '', 0, None, {} are falsy
for v in [0, 1, "", "x", [], [1], None]:
    print(bool(v), v)

5. Bitwise Operators

OpNameExample
&AND0b1100 & 0b1010 == 0b1000
|OR0b1100 | 0b1010 == 0b1110
^XOR0b1100 ^ 0b1010 == 0b0110
~NOT (inverts bits)~5 == -6
<<Left shift1 << 4 == 16
>>Right shift16 >> 2 == 4
bits.py
# Check if a number is a power of two
def is_power_of_two(n):
    return n > 0 and (n & (n - 1)) == 0

for n in [1, 2, 3, 4, 8, 15, 16]:
    print(n, is_power_of_two(n))

# Swap using XOR (just a trick — rarely Pythonic)
a, b = 5, 9
a ^= b; b ^= a; a ^= b
print(a, b)

6. Assignment, Membership & Identity Operators

  • Compound assignment: +=, -=, *=, /=, //=, %=, **=, &=, |=, ^=, <<=, >>=
  • Walrus (PEP 572): := — assigns and returns in one expression (Python 3.8+)
  • Membership: in, not in
  • Identity: is, is not
misc.py
fruits = ["apple", "mango", "jackfruit"]
print("mango" in fruits)          # True
print("orange" not in fruits)     # True

# Walrus operator (Python 3.8+)
data = [1, 2, 3, 4, 5]
if (n := len(data)) > 3:
    print(f"List has {n} items — too many")

7. Precedence — Who Goes First

Operator precedence controls which operation runs first in an expression without parentheses. The partial order (from highest to lowest): ** → unary -/~ → * / // % → + - → shifts → & → ^ → | → comparisons → not → and → or.

Rule of thumb: when in doubt, add parentheses. Code readability is worth more than saved keystrokes.

নিয়ম: সন্দেহ হলে parenthesis ব্যবহার করুন। কয়েকটা অতিরিক্ত bracket দিলে কোডের readability অনেক ভালো হয়।

8. Vocabulary (শব্দভাণ্ডার)

TermMeaningবাংলায়
OperandA value an operator acts on.যে মানের উপর operator কাজ করে।
Short-circuitStop evaluating as soon as result is known.ফলাফল জানা হয়ে গেলে evaluation থামিয়ে দেওয়া।
Truthy / FalsyNon-boolean values that act as True/False in bool context.যে সব non-boolean মান condition-এ True বা False হিসেবে আচরণ করে।
WalrusThe := operator that assigns and returns.:= — একই সাথে assign ও return করে।
PrecedenceOrder of operator evaluation.অপারেটর evaluation-এর ক্রম।

9. Practice Problems

  1. Compute the number of seconds in a year (365 days) using a single expression.
    এক লাইনের একটি expression দিয়ে এক বছরের (৩৬৫ দিন) মোট সেকেন্ড বের করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans1.py
    print(365 * 24 * 60 * 60)
  2. Write a function is_even(n) using the modulus operator.
    Modulus operator ব্যবহার করে is_even(n) ফাংশন লিখুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans2.py
    def is_even(n):
        return n % 2 == 0
    
    for k in range(6):
        print(k, is_even(k))
  3. Using comparison chaining, check whether a number x is strictly between 10 and 20.
    Comparison chaining ব্যবহার করে চেক করুন x 10 ও 20-এর মাঝে আছে কি না।
    ✨ Show Answer (উত্তর দেখুন)
    ans3.py
    x = 15
    print(10 < x < 20)
  4. Explain why [] or "default" evaluates to "default".
    ব্যাখ্যা করুন — [] or "default" কেন "default" দেয়।
    ✨ Show Answer (উত্তর দেখুন)

    Answer: Empty list [] is falsy. The or operator returns the first truthy operand; since [] is falsy it moves on and returns the second operand "default". This is the Pythonic way to provide fallbacks.

    খালি list [] falsy। or প্রথম truthy operand return করে; [] falsy বলে পরবর্তী operand "default" return হয়। এটি Python-এ fallback দেওয়ার idiomatic উপায়।

  5. Check whether 16 is a power of two using only bitwise operators.
    শুধুমাত্র bitwise operator ব্যবহার করে 16 2-এর পাওয়ার কি না যাচাই করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans5.py
    n = 16
    print(n > 0 and (n & (n - 1)) == 0)

Summary — Module 07

Python has a rich operator set. Key points: / always returns float, // is floor division, comparison operators can be chained (0 < x < 10), and/or short-circuit and return an operand (not necessarily a bool), and Python's integers are arbitrary-precision so bit tricks scale without overflow.

মূল কথাগুলো: / সবসময় float, // floor division, comparison chain করা যায় (0 < x < 10), and/or short-circuit এবং operand return করে, এবং Python integer-এ overflow নেই।

Next Module → Input & Output — input(), print(), f-strings।