๐Ÿ Introduction to Python
Module 1 ยท Topic 6

Python Syntax & Indentation Rules

Master Python's unique syntax rules โ€” indentation-based blocks, line continuation, and code structure that makes Python readable.

Theory

Python Syntax Rules:

1. Indentation is Mandatory (Not Optional!)
Python uses indentation (whitespace) to define code blocks. Other languages use { }, but Python uses consistent indentation.

  • Standard: 4 spaces per level (PEP 8 recommendation)
  • Tabs vs spaces: Pick one and be consistent (spaces recommended)
  • Mixing tabs and spaces causes TabError

2. Statements & Line Endings

  • Each line is a statement (no semicolons needed)
  • Multiple statements on one line: use semicolons (discouraged)
  • Long lines: use \ for explicit line continuation or wrap in (), [], {}

3. Code Blocks

  • Blocks start with a colon :
  • Everything indented under it belongs to the block
  • Block ends when indentation returns to previous level

4. Comments

  • Single-line: # comment
  • Multi-line: use consecutive # lines
  • Docstrings: """description""" (first line of function/class/module)
Syntax
# Indentation defines blocks
if True:
    print("Inside if")     # 4 spaces
    if True:
        print("Nested")    # 8 spaces
print("Outside if")        # 0 spaces

# Line continuation
total = (first_value
         + second_value
         + third_value)