Skip to main content

Python Basics

Operators

Complete lesson for Operators using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.

L1

Basics — Operators

Section: Python Basics. Use arithmetic, comparison, logical, bitwise, membership, and identity operators with correct precedence.

What are operators?

  • Operators are symbols (or keywords) that perform an operation on one or more operands and produce a value.
  • Examples: a + b (arithmetic), a > b (comparison), a and b (logical), x in items (membership).
  • Python has no ++ / --; use x += 1 or x = x + 1 instead.
  • Unlike C/Java, logical operators are the words and, or, not — not &&, ||, !.

Types of operators (overview)

  • Python operators are grouped by the kind of work they do.
  • Use this table as a quick map; the sections below expand each category with examples.
CategoryOperatorsPurpose
Arithmetic+ - * / // % **Math, floor divide, power
Comparison (relational)== != < <= > >=Compare values; result is bool
Logicaland or notCombine truth values (short-circuit)
Bitwise& | ^ ~ << >>Bit operations on integers
Assignment= += -= *= /= //= %= **= (+ bitwise forms)Store or update a name
Membershipin / not inTest if a value appears in a container
Identityis / is notTest if two names refer to the same object
Other:= (walrus), ternary x if c else yAssign in an expression; choose a value

Arithmetic operators

  • + - * / // % ** cover add, subtract, multiply, true divide, floor divide, modulo, power.
  • Unary + and - change sign: -x.
  • / on integers yields float; use // when you need an int quotient.
  • Augmented forms: += -= *= /= //= %= **= rebind or update as appropriate.
OperatorNameExampleResult / meaning
+Addition10 + 313
-Subtraction10 - 37
*Multiplication10 * 330
/True division10 / 42.5 (always float)
//Floor division10 // 42 (toward −∞)
%Modulus10 % 42 (remainder)
**Exponent10 ** 2100
-xUnary minus-10Negates the value
x = 10
print(x + 3, x - 3, x * 3, x / 4, x // 4, x % 4, x ** 2)
# Output:
# 13 7 30 2.5 2 2 100

Comparison operators

  • == != < <= > >= compare values and return booleans.
  • Comparisons can chain: 1 < x < 10 means 1 < x and x < 10.
  • Chained comparisons evaluate middle expressions once (important for costly calls).
  • Different types may compare in Python 3 only when ordering is defined — 1 < "a" raises TypeError.
OperatorNameExampleMeaning
==Equal toa == bTrue if values are equal
!=Not equala != bTrue if values differ
>Greater thana > bTrue if a is greater
<Less thana < bTrue if a is smaller
>=Greater or equala >= bTrue if a ≥ b
<=Less or equala <= bTrue if a ≤ b
x = 5
print(x == 5, x != 5, x < 7, 1 < x < 10)
# Output:
# True False True True

Logical operators

  • and, or, not combine truth values.
  • They short-circuit: and stops on first falsy; or stops on first truthy.
  • They return the deciding operand, not necessarily a bool: 3 or 0 is 3.
  • Prefer explicit booleans in APIs; use operand-returning behavior carefully.
OperatorNameExampleMeaning
andLogical ANDa and bFirst falsy operand, else last
orLogical ORa or bFirst truthy operand, else last
notLogical NOTnot aTrue if a is falsy
print(True and False, True or False, not False)
print(0 or 5, 3 and 4, "" or "default")
# Output:
# False True True
# 5 4 default

Membership and identity

  • x in seq tests membership for containers and substrings in strings.
  • x not in seq is the negation.
  • a is b / a is not b test identity; prefer for None checks.
  • For value equality of numbers and strings, use ==.
OperatorNameExampleMeaning
inMembership3 in [1, 2, 3]True if value is present
not inNot membership"z" not in "abc"True if value is absent
isIdentitya is NoneTrue if same object
is notNot identitya is not bTrue if different objects
print("py" in "python")
print(3 in [1, 2, 3])
a = None
print(a is None)
# Output:
# True
# True
# True

Bitwise operators

  • Work on integers: & | ^ ~ << >> for and, or, xor, invert, shifts.
  • Useful for flags, masks, and low-level protocols; less common in day-one apps.
  • ~x equals -x - 1 because of two’s complement style representation.
  • Shifts: x << n multiplies by 2**n; x >> n divides by 2**n (floor toward -∞ for negatives — be careful).
OperatorNameExampleResult
&Bitwise AND5 & 31 (101 & 011)
|Bitwise OR5 | 37 (101 | 011)
^Bitwise XOR5 ^ 36 (101 ^ 011)
~Bitwise NOT~5-6 (~x == -x - 1)
<<Left shift5 << 110
>>Right shift5 >> 12

Assignment operators

  • = binds a name to a value. Compound forms update using the current value.
  • Augmented assignment on mutables may update in place (list +=); on immutables it rebinds.
  • Ordinary = is a statement — not usable inside expressions (use := for that).
  • Bitwise compounds also exist: &= |= ^= <<= >>=.
OperatorExampleEquivalent to
=a = 5Bind a to 5
+=a += 2a = a + 2
-=a -= 2a = a - 2
*=a *= 2a = a * 2
/=a /= 2a = a / 2
//=a //= 2a = a // 2
%=a %= 2a = a % 2
**=a **= 2a = a ** 2
a = 10
a += 5
a //= 3
print(a)
# Output:
# 5

Precedence overview

  • Higher precedence binds tighter: ** above unary, then * / // %, then + -, then shifts, bitwise, comparisons, not, and, or.
  • When unsure, add parentheses — clarity beats memorizing the full table.
  • Assignment and augmented assignment are statements, not expression operators (walrus := is the exception).
  • String/list + and * are sequence ops with similar precedence ideas to arithmetic.
Higher → lower (summary)Examples
Parentheses( ... )
Exponent** (right-associative)
Unary+x, -x, ~x
Multiply / divide* / // %
Add / subtract+ -
Shifts<< >>
Bitwise& then ^ then |
Comparisons / membership / identity== != <, in, is, …
Boolean not / and / ornot, and, or
Conditional expressionx if c else y
Walrus:=
print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 ** 3 ** 2)
print((2 ** 3) ** 2)
# Output:
# 14
# 20
# 512
# 64

Walrus operator :=

  • Python 3.8+ assignment expression binds a name inside an expression.
  • Useful in while loops and comprehensions to avoid double work.
  • Do not overuse — if it hurts readability, use a normal assignment.
  • It is an expression, unlike regular =.
text = "abcd"
if (n := len(text)) > 3:
    print("length", n)
# Output:
# length 4

Operator overloading preview

  • Objects can define special methods (__add__, __eq__, …) so operators work on your types.
  • + on strings concatenates; on lists concatenates; on ints adds — same symbol, different meaning.
  • * repeats sequences: "ab" * 3 is "ababab".
  • Always check types when reading unfamiliar code that uses operators heavily.
print("ha" * 3)
print([0, 1] * 2)
print([1, 2] + [3])
# Output:
# hahaha
# [0, 1, 0, 1]
# [1, 2, 3]

Common mistakes

  • Using = inside conditions — that is assignment; comparisons need == (walrus is intentional).
  • Assuming and/or always return True/False.
  • Writing 1 < x > 0 thinking it means something else — learn chaining rules.
  • Mixing floor division expectations from other languages (C truncates toward zero; Python floors).
print(-7 // 2)
print(True and 0)
print(False or "fallback")
# Output:
# -4
# 0
# fallback
L2

Advanced — Operators

Short-circuit patterns

  • obj = cache or compute() style defaults rely on falsy checks — empty containers count as falsy.
  • Guard clauses: if obj is not None and obj.is_ready(): avoids attribute errors via short-circuit.
  • Order conditions from cheapest/most likely to fail first for speed and safety.
  • Do not put required side effects on the right of and/or unless intentional.
config = ""
value = config or "default"
print(value)
nums = [1, 2, 3]
print(nums and nums[0])
# Output:
# default
# 1

Rich comparisons

  • Objects may implement __lt__, __eq__, etc.; functools.total_ordering can fill gaps.
  • Sorting uses < comparisons; inconsistent __eq__/__hash__ breaks sets/dicts.
  • For floats, prefer math.isclose over == when tolerance matters.
  • In Python 3, sorting mixed incompatible types fails loudly — good.

Bitwise flags idiom

  • Define powers of two as flags and combine with |; test with &.
  • Clear a flag with & ~FLAG; toggle with ^.
  • Prefer enum.Flag in modern code for readability.
  • Document bit layouts when talking to hardware or binary protocols.
READ, WRITE, EXEC = 1, 2, 4
mode = READ | WRITE
print(mode, bool(mode & WRITE), bool(mode & EXEC))
mode ^= WRITE
print(mode, bool(mode & WRITE))
# Output:
# 3 True False
# 1 False

Precedence gotchas with bitwise vs comparisons

  • Bitwise operators bind tighter than comparisons? Actually comparisons bind less tightly than bitwise — a & b == c parses as a & (b == c) … wait: in Python, comparisons have lower precedence than bitwise, so a & b == c is (a & b) == c. Confirm with docs when mixing.
  • Always parenthesize mixed bitwise and comparison expressions.
  • Shift operators sit between additive and bitwise-and in the table — parenthesize shifts in complex math.
  • Read the language reference table once; then default to parentheses in real code.
a, b, c = 5, 3, 1
print((a & b) == c)
print(a & (b == c))
# Output:
# True
# 0
L3

Tricky Interview Points

Q1) What is the difference between / and //?

Answer / is true division (float). // is floor division toward negative infinity.

Q2) What does short-circuit evaluation mean?

Answer and/or stop evaluating once the result is known, skipping later operands.

Q3) What does and return?

Answer The first falsy operand, or the last operand if all are truthy — not always a bool.

Q4) How does comparison chaining work?

Answer a < b < c means a < b and b < c, evaluating b once.

Q5) When should you use is?

Answer Primarily for None (and sometimes singletons). Use == for value equality.

Q6) What is the walrus operator?

Answer := assigns inside an expression (Python 3.8+), e.g. if (n := len(s)) > 10:.

Q7) What is ** associativity?

Answer Right-associative: 2 ** 3 ** 2 equals 2 ** (3 ** 2) = 512.

Q8) Explain in for strings vs lists.

Answer For strings it tests substring membership; for lists it tests element equality membership.

Q9) What is ~5?

Answer Bitwise invert; equals -6 because ~x == -x - 1.

Q10) Why parenthesize mixed operators?

Answer To make intent clear and avoid precedence mistakes, especially with bitwise and comparisons.

Q11) What does "ab" * 3 produce?

Answer "ababab" — sequence repetition, not numeric multiplication.

Q12) Is = an operator in expressions?

Answer Ordinary = is a statement. Only := is an assignment expression.

L4

Simple Programs

Arithmetic battery

a, b = 23, 5
for op, val in [
    ("+", a + b),
    ("-", a - b),
    ("*", a * b),
    ("/", a / b),
    ("//", a // b),
    ("%", a % b),
    ("**", a ** 2),
]:
    print(op, val)
# Output:
# + 28
# - 18
# * 115
# / 4.6
# // 4
# % 3
# ** 529

Logic and chaining

x = 7
print(1 <= x <= 10)
print(x < 5 or x > 6)
print(not (x == 0))
# Output:
# True
# True
# True

Membership drills

vowels = "aeiou"
print("e" in vowels, "x" not in vowels)
print(2 in (1, 2, 3), 4 not in [1, 2, 3])
# Output:
# True True
# True True

Bitwise masks

flags = 0b1101
mask = 0b0100
print(bin(flags & mask))
print(bin(flags | mask))
print(bin(flags ^ mask))
# Output:
# 0b100
# 0b1101
# 0b1001

Precedence parentheses

print(3 + 4 * 2)
print(3 + 4 * 2 ** 2)
print((3 + 4) * 2 ** 2)
# Output:
# 11
# 19
# 28

Walrus in a loop

data = ["one", "three", "seven"]
i = 0
while (i < len(data)) and (n := len(data[i])) < 5:
    print(data[i], n)
    i += 1
print("stopped at", i)
# Output:
# one 3
# stopped at 1
L5

Problem Solving Tricks

  • Chain comparisons for range checks: 0 <= x < n.
  • Use x or default only when falsy values should trigger the default.
  • Parenthesize every bitwise + comparison mix.
  • Remember ** is right-associative — unique among arithmetic ops.
  • Prefer math.isclose for float equality in scientific code.
  • Use divmod when you need both quotient and remainder.
  • Replace nested if with and guards when both conditions are simple.
  • For flags, enum.Flag reads clearer than raw ints in large projects.
  • In debugging, print intermediate results instead of trusting mental precedence.
L6

Practice Programs List

  1. Evaluate on paper: 2 + 3 * 4 ** 2 // 8 - 1, then verify in Python.
  2. Write expressions using and/or that return non-bool values and predict results.
  3. Implement a permission check with bitwise flags READ/WRITE/EXEC.
  4. Show three examples of comparison chaining with True and False outcomes.
  5. Demonstrate short-circuit by putting a call that would fail on the right of and.
  6. Rewrite an assignment-plus-check using the walrus operator, then without it.
  7. Prove with code that -7 // 2 is -4.
  8. Test "in" for substring vs list-of-characters membership differences you invent.
  9. Create a table printing a&b, a|b, a^b for a=0..3, b=0..3.
  10. Find a precedence bug in (a < b) == c vs a < b == c style expressions and explain.
  11. Use augmented assignment five times in a running total script.