Assignment binds a name to an object. Rebinding a name does not change other names.
name = expressionExample a = [1]
b = a
a = [2]
print(a, b)Watch for: Two names may refer to the same mutable object; distinguish rebinding from mutation.
Practise this topic → A type describes the operations a value supports. Conversion constructs a value of another type.
type(value); int(text); float(text); str(value)Example print(type(3).__name__, int("42"), str(False))Watch for: int("3.5") raises ValueError. int(3.9) truncates toward zero, not toward the nearest integer.
Practise this topic → Conditions test truthiness; and/or return operands, while not returns a boolean.
value or fallback; a and b; not valueExample print(bool([]), bool("0"))
print(0 or 10, "" or "guest")Result False True
10 guest Watch for: A fallback using or replaces every falsy value, including zero. Use an explicit None check when zero is valid.
Practise this topic → Numeric operators calculate values; floor division rounds the quotient down.
a / b; a // b; a % b; a ** bExample print(7 / 2, 7 // 2, -7 // 2, 7 % 2, 2 ** 3)Watch for: Division by zero raises ZeroDivisionError. Binary floating point cannot represent every decimal exactly.
Practise this topic → Equality compares values, identity compares objects, and membership asks whether an item is present.
a == b; a is b; item in containerExample a = [1]
b = [1]
print(a == b, a is b, 1 in a)
print(1 < 2 < 3)Result True False True
True Watch for: Use is None for the singleton None. Do not use is to compare numbers or strings.
Practise this topic → An index selects one Unicode code point from a string. Negative indices count from the end.
text[index]; text[-1]Example s = "CANTEEN"
print(s[0], s[-1], len(s))Watch for: An invalid single index raises IndexError. A user-perceived character can contain multiple code points.
Practise this topic → A slice selects positions from start toward stop, excluding stop, at the chosen step.
Try different slice boundaries Choose the boundaries. Follow the selected positions. A slice visits positions toward its stop boundary. The stop position is excluded; reversing the step changes the direction.
Text start stop step
Middle slice Reverse Last three
0 C -7
1 A -6
2 N -5
3 T -4
4 E -3
5 E -2
6 N -1
s[1:4]→ "ANT"
Interactive model of Python slicing over Unicode code points. A visible character may contain several code points. Blank bounds are omitted, which differs from explicitly using -1 with a negative step.
text[start:stop:step]Example s = "CANTEEN"
print(s[1:4], s[-3:], s[::2], s[::-1])
print(repr(s[99:]))Result ANT EEN CNEN NEETNAC
'' Watch for: Out-of-range bounds are clipped. Step zero raises ValueError. stop-start is not a general slice-length formula.
Practise this topic → String methods return results; they do not modify the original string.
text.strip(); text.split(sep); separator.join(parts)Example raw = " Asha,Rao "
parts = raw.strip().split(",")
print(" ".join(parts))
print(repr(raw))Result Asha Rao
' Asha,Rao ' Watch for: strip(chars) removes any listed characters from both ends, not an exact prefix. Use removeprefix for a prefix.
Practise this topic → An f-string evaluates expressions and formats the resulting values.
f"{expression:format_spec}"Example price = 12.5
print(f"Total: {price:.2f}")
print(f"{7:04d}")Watch for: Formatting creates text. It does not change the numeric value or solve decimal arithmetic precision.
Practise this topic → if/elif selects the first true branch; match checks a subject against patterns.
if condition: ...
elif condition: ...
else: ...Example score = 82
if score >= 80:
print("distinction")
elif score >= 50:
print("pass")
else:
print("retry")Watch for: Order specific conditions before broader ones. A bare name in a match pattern captures a value rather than comparing an existing variable.
Practise this topic → A for loop requests successive values from an iterable. enumerate adds positions; zip combines streams.
for value in iterable: ...
enumerate(items, start=1); zip(left, right)Example for number, (name, score) in enumerate(zip(["Asha", "Om"], [8, 9]), start=1):
print(number, name, score)Watch for: zip stops at the shortest iterable by default. zip(..., strict=True) detects unequal lengths on Python 3.10+.
Practise this topic → range describes integer steps without storing a list. Loop else runs if no break occurred.
range(stop); range(start, stop, step)
for ...: ...
else: ...Example print(list(range(5, 0, -2)))
for n in [1, 3, 5]:
if n % 2 == 0:
break
else:
print("no even value")Result [5, 3, 1]
no even value Watch for: The stop is excluded. continue does not suppress loop else; break does.
Practise this topic → return supplies a value to the caller. print sends text to an output stream.
def name(parameters):
return expressionExample def add_fee(subtotal):
return subtotal + 20
bill = add_fee(100)
print(bill - 10)Watch for: Falling off the end returns None. A printed value cannot be used as the function result.
Practise this topic → Parameters bind caller inputs; / and * restrict how arguments can be supplied.
def f(positional_only, /, normal, *, keyword_only): ...Example def quote(amount, /, tax=0, *, currency="INR"):
return amount + tax, currency
print(quote(100, 18, currency="INR"))Watch for: A default is evaluated when def executes. Use None and create a fresh container inside for a per-call mutable default.
Practise this topic → A tuple can carry several results. *args packs extra positional arguments and **kwargs packs keyword arguments.
a, b = pair
f(*values, **options)Example def summarize(*values, **options):
return sum(values), options.get("unit", "items")
amount, unit = summarize(*[2, 3], unit="kg")
print(amount, unit)Watch for: Unpacking must match the expected shape unless a starred target collects the remainder.
Practise this topic → try/except handles selected exceptions; finally runs cleanup when control leaves the try statement.
try: ...
except ValueError as error: ...
else: ...
finally: ...Example try:
number = int("bad")
except ValueError:
print("invalid number")
finally:
print("finished")Result invalid number
finished Watch for: Catch the narrow failures you can handle. Returning from finally can hide a pending exception.
Practise this topic → A list is an ordered mutable collection. A shallow copy creates a new outer container.
items.append(value); items.extend(values); items.copy()Example a = [[1]]
b = a.copy()
b[0].append(2)
print(a, b)
print(a.append([3]))Result [[1, 2]] [[1, 2]]
None Watch for: append and sort mutate in place and return None. Shallow copies still share nested objects.
Practise this topic → A comprehension constructs a collection from an iterable with optional filtering.
[expression for item in iterable if condition]Example squares = [n * n for n in range(6) if n % 2 == 0]
print(squares)
print({n: n * n for n in range(3)})Result [0, 4, 16]
{0: 0, 1: 1, 2: 4} Watch for: The if after the loop filters items. A conditional expression before the loop chooses a value for every item.
Practise this topic → A dictionary maps hashable keys to values and preserves insertion order.
mapping[key]; mapping.get(key, default); mapping.items()Example counts = {"tea": 2}
print(counts.get("coffee", 0))
for name, count in counts.items():
print(name, count)Watch for: [] raises KeyError for a missing key. get does not insert its default. setdefault may insert it.
Practise this topic → A set holds distinct hashable values and supports membership and set algebra.
a | b; a & b; a - b; a ^ bExample a, b = {1, 2}, {2, 3}
print(sorted(a | b), sorted(a & b), sorted(a - b))Watch for: {} is an empty dictionary; set() is an empty set. Do not rely on set iteration order.
Practise this topic → A class defines behavior; instances hold their own state through attributes.
class Name:
def __init__(self, value): ...Example class Counter:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
c = Counter()
c.increment()
print(c.value)Watch for: A mutable class attribute is shared across instances unless shadowed. Initialize per-instance lists in __init__.
Practise this topic → A hashable object has a stable hash and equality behavior suitable for dictionary/set membership.
hash(value); {(key_part_1, key_part_2): value}Example location = (12, 18)
print({location: "sensor"}[location])Watch for: A tuple is hashable only if all its elements are hashable. Being immutable alone does not prove an arbitrary object is hashable.
Practise this topic → An iterable supplies an iterator. An iterator retains a position and produces values through next.
iterator = iter(iterable)
next(iterator, default)Example source = [10, 20]
a, b = iter(source), iter(source)
print(next(a), next(a), next(b))
print(next(a, "end"))Watch for: A consumed iterator is not automatically reset. Creating an iterator from a list can start an independent traversal.
Practise this topic → A function containing yield creates a generator whose execution suspends between yielded values.
def values():
yield expressionExample def values():
print("started")
yield 10
g = values()
print("created")
print(next(g))Watch for: Calling the generator function does not execute its body immediately. Exhaustion ends that generator instance.
Practise this topic → A generator expression computes values as requested; islice limits consumption.
(expression for item in iterable)
itertools.islice(iterator, count)Example from itertools import islice
g = (n * n for n in range(100))
print(list(islice(g, 3)))
print(next(g))Watch for: Laziness does not make retained source data disappear. Some operations buffer or consume the entire input.
Practise this topic → Functions resolve names through local, enclosing, global and built-in scopes. Closures retain bindings.
nonlocal name; global nameExample def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
c = make_counter()
print(c(), c())Watch for: Assignment makes a name local unless declared otherwise. Late-bound closures observe a binding at call time.
Practise this topic → A decorator transforms a function when its definition executes. wraps preserves useful metadata.
@decorator
def function(...): ...Example from functools import wraps
def traced(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
return wrapper
@traced
def total(a, b):
return a + b
print(total(2, 3), total.__name__)Watch for: Stacked decorators apply from the bottom upward. A synchronous wrapper does not automatically await an async function.
Practise this topic → Counter counts hashable values; defaultdict creates a missing value when accessed with [].
Counter(iterable); defaultdict(factory)Example from collections import Counter, defaultdict
print(sorted(Counter("banana").items()))
groups = defaultdict(list)
groups["fruit"].append("pear")
print(dict(groups))Result [('a', 3), ('b', 1), ('n', 2)]
{'fruit': ['pear']} Watch for: defaultdict.get does not invoke the factory. Counter entries may have zero or negative counts.
Practise this topic → deque supports both ends; heapq keeps the smallest item at the root of a list-based min-heap.
deque.append; deque.popleft; heappush; heappopExample from collections import deque
from heapq import heappush, heappop
q = deque([1, 2]); q.append(3)
heap = []; heappush(heap, 8); heappush(heap, 2)
print(q.popleft(), heappop(heap))Watch for: A heap is not a globally sorted list. Repeated heappop operations retrieve items in priority order.
Practise this topic → Path represents filesystem paths; a with statement gives a resource a defined cleanup boundary.
Path("data") / "input.csv"
with path.open(encoding="utf-8") as handle: ...Example from pathlib import Path
p = Path("data") / "input.csv"
print(p.name, p.suffix)Watch for: Filesystem operations require appropriate permissions. Browser files live in a virtual filesystem unless explicitly exported.
Practise this topic → str contains Unicode text; bytes contains integer byte values. Encoding and decoding cross that boundary.
text.encode("utf-8"); data.decode("utf-8")Example text = "café"
data = text.encode("utf-8")
print(len(text), len(data), data.decode("utf-8"))Watch for: The encoding must match the data. Ignoring decoding errors can silently lose information.
Practise this topic → JSON represents a restricted set of data types; dumps produces text and loads parses it.
json.dumps(value); json.loads(text)Example import json
text = json.dumps({"ok": True, "items": [1, 2]}, sort_keys=True)
print(text)
print(json.loads(text)["ok"])Result {"items": [1, 2], "ok": true}
True Watch for: JSON object keys are strings. Python-specific types need an explicit representation; parsing is not schema validation.
Practise this topic → The csv module handles quoting and delimiters so a comma inside a field remains data.
csv.DictReader(handle); csv.DictWriter(handle, fieldnames=...)Example import csv, io
rows = csv.DictReader(io.StringIO('name,note\nAsha,"tea, please"\n'))
print(next(rows)["note"])Watch for: For real files use open(..., newline="", encoding="utf-8"). A split(",") is not a CSV parser.
Practise this topic → Regular expressions recognize text patterns; fullmatch checks the entire input.
re.search(pattern, text); re.fullmatch(pattern, text)Example import re
print(bool(re.fullmatch(r"[A-Z]{2}[0-9]{3}", "AB123")))
print(re.findall(r"[0-9]+", "a12 b7"))Watch for: search can match a substring. Avoid ambiguous nested repetition with untrusted inputs; a match is not domain validation.
Practise this topic → Import locates and initializes a module, normally caching it in sys.modules. __name__ identifies its execution context.
import package.module
if __name__ == "__main__": ...Example import math
print(math.isqrt(17))Watch for: A local file named like a standard module can shadow it. An import may execute module-level code.
Practise this topic → A virtual environment isolates an interpreter environment and its installed packages.
python -m venv .venv
python -m pip install package
python -m pip --versionExample import sys
print(isinstance(sys.executable, str))Watch for: Activate using the command for your shell, or invoke the environment interpreter explicitly. Confirm which interpreter pip installs into.
Practise this topic → raise from connects an application error to the lower-level failure that caused it.
raise DomainError("message") from errorExample try:
try:
int("bad")
except ValueError as error:
raise RuntimeError("invalid record") from error
except RuntimeError as error:
print(type(error.__cause__).__name__)Watch for: Do not swallow failures or expose secrets in messages. Preserve enough context for diagnosis.
Practise this topic → A test compares observed behavior against a stated contract on chosen examples.
def test_behavior():
assert actual == expectedExample def divide(total, count):
return total / count
assert divide(10, 2) == 5
print("contract example passed")Result contract example passed Watch for: Use pytest locally for its discovery, parametrization and fixtures. Passing samples does not prove correctness for every input.
Practise this topic → Annotations describe expected types for tools and readers; Python does not enforce them automatically.
def parse(text: str) -> int | None: ...Example def parse(text: str) -> int | None:
try:
return int(text)
except ValueError:
return None
print(parse("7"), parse("bad"))Watch for: Run a configured type checker separately. A cast informs the checker; it does not validate a value at runtime. Union | syntax needs Python 3.10+.
Practise this topic → A context manager defines entry and exit behavior around a with block.
with resource() as value: ...Example from contextlib import contextmanager
@contextmanager
def owned():
print("enter")
try:
yield "resource"
finally:
print("exit")
with owned() as value:
print(value)Result enter
resource
exit Watch for: Exit logic must define what happens on failures. Returning True from __exit__ suppresses the exception.
Practise this topic → An async function call creates a coroutine. Awaiting or scheduling it arranges execution.
await operation()
asyncio.create_task(operation())
async with asyncio.TaskGroup() as group: ...Example import inspect
async def fetch():
return 42
coroutine = fetch()
print(inspect.iscoroutine(coroutine))
coroutine.close()Watch for: Blocking calls still block an event-loop thread. Use cleanup in finally and normally re-raise cancellation after cleanup. TaskGroup needs Python 3.11+.
Practise this topic →