MOD-01 · Sequence #1 · Python Basics

Python Syntax & Indentation

Unlike languages like C, Java, or C++ that delimit blocks using curly braces {}, Python uses syntactic indentation. Whitespace is an actual lexical token in Python grammar. Mastering indentation levels and block scoping is the foundational prerequisite of all Python programs.

Live Interactive Code Snippet (Python 3.12 CPython WASM) Open in Practice Mode →
if 5 > 2:
    print("Five is greater than two!")

Core Principles & Mental Models

1. The Lexical Significance of Whitespace

INDENT and DEDENT Tokens in the Lexer

  • In Python, indentation is not a cosmetic styling choice; it is a syntactical requirement enforced by the CPython parser.
  • When the Python lexical analyzer scans source code, it generates INDENT and DEDENT tokens whenever the leading whitespace on a newline increases or decreases.
  • Standard PEP 8 convention dictates using exactly 4 spaces per indentation level. Never mix physical TAB characters with spaces in Python 3, which raises a TabError.
def calculate_grade(score):
    # 4 spaces indentation creates a function block
    if score >= 90:
        # 8 spaces creates a nested conditional block
        grade = "A"
    else:
        grade = "B"
    return grade

print("Grade for 95:", calculate_grade(95))
💡 Key Takeaway: In Python, every colon (:) introduces an indented block. Any statement indented to the same depth belongs to the same logical block.

2. Statement Termination & Line Continuations

No Semicolons & Implicit vs. Explicit Continuation

  • In Python, statements terminate at the end of the line (newline character). Semicolons (;) are optional and generally considered unpythonic.
  • When a single statement spans multiple lines, Python provides implicit continuation inside parentheses (), square brackets [], or curly braces {}.
  • Explicit line continuation using a backslash (\) is supported but discouraged when parenthesized expressions are available.
# Preferred: Implicit continuation within parentheses
total = (
    100
    + 200
    + 300
)
print("Total:", total)
💡 Key Takeaway: Wrap complex multiline expressions in parentheses instead of using backslashes for clean, readable syntax.

Interactive Walkthrough Examples

Basic Indentation Hierarchy (Basic)

Demonstrating nested conditional blocks and uniform 4-space alignment.

threshold = 10
reading = 14

if reading > threshold:
    difference = reading - threshold
    print(f"Reading exceeds threshold by {difference}")
    if difference > 5:
        print("Alert: Critical excess!")
    else:
        print("Notice: Moderate excess.")
print("Evaluation complete.")

Explanation: Notice that print("Evaluation complete.") is at indent level 0, executing unconditionally after the if-else block finishes.

Multiline Expressions & Parentheses (Intermediate)

Using implicit continuation in function calls and collections.

scores = [
    88, 92, 79,
    95, 100, 84
]

average = (
    sum(scores)
    / len(scores)
)

print(f"Sample size: {len(scores)}, Average: {average:.2f}")

Explanation: Enclosing calculations in parentheses allows clean formatting without syntax errors.

Common Misconceptions & Exam Traps

Common Pitfall: Mixing Tabs and Spaces (TabError)

Python 3 forbids mixing tabs and spaces for indentation within the same block because tab stops differ across editors.

Buggy Code
def faulty():
    x = 10  # 4 spaces
	y = 20  # 1 tab character (causes TabError in Python 3)
Correct Solution
def clean():
    x = 10  # 4 spaces
    y = 20  # 4 spaces consistently

Exam Trap Note: In exam grading scripts, copy-pasting code with tabs often triggers an immediate TabError: inconsistent use of tabs and spaces in indentation.

Common Pitfall: Unexpected Indentation on Top-Level Statements

Statements outside any control structure or function must begin at the first column (zero indentation).

Buggy Code
print("Starting program")
  x = 5  # IndentationError: unexpected indent
Correct Solution
print("Starting program")
x = 5  # Aligned to column 0

Exam Trap Note: Watch out for leading spaces when writing code outside classes and functions.

Conceptual Knowledge Self-Check Quiz

Q1: What error does Python 3 raise when tabs and spaces are mixed in the same file indentation?

  1. SyntaxError: invalid block
  2. TabError: inconsistent use of tabs and spaces
  3. TypeError: cannot mix token types
  4. IndentationWarning

Python 3 strictly disallows mixing tabs and spaces, raising a TabError.

Q2: Which character in Python introduces a new indented block?

  1. Semicolon (;)
  2. Curly brace ({)
  3. Colon (:)
  4. Arrow (->)

In Python compound statements (def, if, while, for, class), a colon (:) signals the start of an indented block.

Algorithmic Practice Challenges

Idiomatic Best Practices

  • ✅ Always configure your code editor to insert 4 spaces when pressing the Tab key.
  • ✅ Limit line lengths to 79-88 characters as recommended by PEP 8.
  • ✅ Use blank lines sparingly to separate functions and logical sections of code.

All 26 Curriculum Modules