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.
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
++/--; usex += 1orx = x + 1instead. - 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.
| Category | Operators | Purpose |
|---|---|---|
| Arithmetic | + - * / // % ** | Math, floor divide, power |
| Comparison (relational) | == != < <= > >= | Compare values; result is bool |
| Logical | and or not | Combine truth values (short-circuit) |
| Bitwise | & | ^ ~ << >> | Bit operations on integers |
| Assignment | = += -= *= /= //= %= **= (+ bitwise forms) | Store or update a name |
| Membership | in / not in | Test if a value appears in a container |
| Identity | is / is not | Test if two names refer to the same object |
| Other | := (walrus), ternary x if c else y | Assign 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 yieldsfloat; use//when you need an int quotient.- Augmented forms:
+= -= *= /= //= %= **=rebind or update as appropriate.
| Operator | Name | Example | Result / meaning |
|---|---|---|---|
+ | Addition | 10 + 3 | 13 |
- | Subtraction | 10 - 3 | 7 |
* | Multiplication | 10 * 3 | 30 |
/ | True division | 10 / 4 | 2.5 (always float) |
// | Floor division | 10 // 4 | 2 (toward −∞) |
% | Modulus | 10 % 4 | 2 (remainder) |
** | Exponent | 10 ** 2 | 100 |
-x | Unary minus | -10 | Negates 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 < 10means1 < 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"raisesTypeError.
| Operator | Name | Example | Meaning |
|---|---|---|---|
== | Equal to | a == b | True if values are equal |
!= | Not equal | a != b | True if values differ |
> | Greater than | a > b | True if a is greater |
< | Less than | a < b | True if a is smaller |
>= | Greater or equal | a >= b | True if a ≥ b |
<= | Less or equal | a <= b | True if a ≤ b |
x = 5
print(x == 5, x != 5, x < 7, 1 < x < 10)
# Output:
# True False True True Logical operators
and,or,notcombine truth values.- They short-circuit:
andstops on first falsy;orstops on first truthy. - They return the deciding operand, not necessarily a bool:
3 or 0is3. - Prefer explicit booleans in APIs; use operand-returning behavior carefully.
| Operator | Name | Example | Meaning |
|---|---|---|---|
and | Logical AND | a and b | First falsy operand, else last |
or | Logical OR | a or b | First truthy operand, else last |
not | Logical NOT | not a | True 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 seqtests membership for containers and substrings in strings.x not in seqis the negation.a is b/a is not btest identity; prefer forNonechecks.- For value equality of numbers and strings, use
==.
| Operator | Name | Example | Meaning |
|---|---|---|---|
in | Membership | 3 in [1, 2, 3] | True if value is present |
not in | Not membership | "z" not in "abc" | True if value is absent |
is | Identity | a is None | True if same object |
is not | Not identity | a is not b | True 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.
~xequals-x - 1because of two’s complement style representation.- Shifts:
x << nmultiplies by 2**n;x >> ndivides by 2**n (floor toward -∞ for negatives — be careful).
| Operator | Name | Example | Result |
|---|---|---|---|
& | Bitwise AND | 5 & 3 | 1 (101 & 011) |
| | Bitwise OR | 5 | 3 | 7 (101 | 011) |
^ | Bitwise XOR | 5 ^ 3 | 6 (101 ^ 011) |
~ | Bitwise NOT | ~5 | -6 (~x == -x - 1) |
<< | Left shift | 5 << 1 | 10 |
>> | Right shift | 5 >> 1 | 2 |
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:
&= |= ^= <<= >>=.
| Operator | Example | Equivalent to |
|---|---|---|
= | a = 5 | Bind a to 5 |
+= | a += 2 | a = a + 2 |
-= | a -= 2 | a = a - 2 |
*= | a *= 2 | a = a * 2 |
/= | a /= 2 | a = a / 2 |
//= | a //= 2 | a = a // 2 |
%= | a %= 2 | a = a % 2 |
**= | a **= 2 | a = 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 / or | not, and, or |
| Conditional expression | x 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
whileloops 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" * 3is"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/oralways returnTrue/False. - Writing
1 < x > 0thinking 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 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/orunless 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_orderingcan fill gaps. - Sorting uses
<comparisons; inconsistent__eq__/__hash__breaks sets/dicts. - For floats, prefer
math.iscloseover==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.Flagin 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 == cparses asa & (b == c)… wait: in Python, comparisons have lower precedence than bitwise, soa & b == cis(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 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.
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 Problem Solving Tricks
- Chain comparisons for range checks:
0 <= x < n. - Use
x or defaultonly when falsy values should trigger the default. - Parenthesize every bitwise + comparison mix.
- Remember
**is right-associative — unique among arithmetic ops. - Prefer
math.isclosefor float equality in scientific code. - Use
divmodwhen you need both quotient and remainder. - Replace nested
ifwithandguards when both conditions are simple. - For flags,
enum.Flagreads clearer than raw ints in large projects. - In debugging, print intermediate results instead of trusting mental precedence.
Practice Programs List
- Evaluate on paper:
2 + 3 * 4 ** 2 // 8 - 1, then verify in Python. - Write expressions using
and/orthat return non-bool values and predict results. - Implement a permission check with bitwise flags READ/WRITE/EXEC.
- Show three examples of comparison chaining with True and False outcomes.
- Demonstrate short-circuit by putting a call that would fail on the right of
and. - Rewrite an assignment-plus-check using the walrus operator, then without it.
- Prove with code that
-7 // 2is-4. - Test
"in"for substring vs list-of-characters membership differences you invent. - Create a table printing
a&b,a|b,a^bfor a=0..3, b=0..3. - Find a precedence bug in
(a < b) == cvsa < b == cstyle expressions and explain. - Use augmented assignment five times in a running total script.