Significant Whitespace
Indentation is syntax, not style
Section titled “Indentation is syntax, not style”In TypeScript, indentation is cosmetic. A linter enforces it for readability, but the compiler ignores it entirely — your code runs the same with zero indentation or inconsistent spacing. In Python, indentation is part of the grammar. The interpreter uses it to determine where a block begins and ends. There are no curly braces and no end keywords.
This is not a quirk — it is a deliberate design decision that forces readable code by construction.
if, for, and function blocks
Section titled “if, for, and function blocks”// TypeScript: braces delimit every blockfunction classify(n: number): string { if (n > 0) { return "positive"; } else if (n < 0) { return "negative"; } else { return "zero"; }}
for (let i = 0; i < 3; i++) { if (i % 2 === 0) { console.log(`${i} is even`); }}# Python: indentation delimits every blockdef classify(n: int) -> str: if n > 0: return "positive" elif n < 0: return "negative" else: return "zero"
for i in range(3): if i % 2 == 0: print(f"${i} is even")Key syntax differences to notice:
- The
functionkeyword becomesdef, followed by the function name and a colon. else ifin TypeScript iselifin Python (no separateelse if).- Every block-opening line ends with a colon (
:). - The conventional indent is 4 spaces. Tabs work but mixing tabs and spaces raises a
TabError.
IndentationError: Python’s most beginner-visible error
Section titled “IndentationError: Python’s most beginner-visible error”If you get the indentation wrong, Python raises an IndentationError before the code even runs. This is the Python equivalent of a TypeScript “unexpected token” compile error.
// TypeScript: this still runs (just ugly style)function add(a: number, b: number) {return a + b; // no indent — TS doesn't care}# Python: this raises IndentationErrordef add(a: int, b: int) -> int:return a + b # missing indent — SyntaxError at parse time
# Correct version:def add(a: int, b: int) -> int: return a + b # 4 spacesNested blocks
Section titled “Nested blocks”Nesting works by adding another level of indentation for each block. Python’s parser tracks the indentation level, so there is no limit to nesting depth — though the Zen of Python advises keeping it flat.
// TypeScript nested blocksfunction processMatrix(matrix: number[][]): void { for (const row of matrix) { for (const cell of row) { if (cell > 0) { console.log(`positive: ${cell}`); } } }}# Python nested blocksdef process_matrix(matrix: list[list[int]]) -> None: for row in matrix: for cell in row: if cell > 0: print(f"positive: ${cell}")Try it
Section titled “Try it”# Python uses indentation — no curly braces neededdef greet(name): if name: print(f"Hello, {name}!") else: print("Hello, stranger!")
greet("Alice")greet("")
for i in range(3): if i % 2 == 0: print(f"{i} is even") else: print(f"{i} is odd")Loading Python runtime (first run only)…