Python Syntax, Indentation & Comments

๐Ÿ Python 3.12+ ๐ŸŸข Chapter 2 of 65 ๐Ÿ“‚ Phase 1: Python Basics ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: Whitespace Block Rules ยท IndentationError ยท PEP 8 Style Guide ยท Comments ยท Docstrings
Master Python syntax architecture: 4-space whitespace indentation, elimination of curly braces, PEP 8 style standards, single/multi-line comments, and runtime docstrings.
1Why Whitespace Indentation Matters (No Curly Braces)

In most programming languages (C, C++, Java, JavaScript, Rust), code blocks are demarcated using curly braces { ... }, and indentation is purely cosmetic. In Python, whitespace indentation defines the logical block hierarchy of your program.

This design choice (known as the off-side rule) ensures that every Python codebase is visually uniform, readable, and eliminates entire classes of syntax bugs like dangling-else ambiguity.

The Indentation Rules:

  1. A colon : signals the start of a new indented code block (after if, elif, else, for, while, def, class, try, with).
  2. Every line within that block must be indented by exactly 4 spaces (the official PEP 8 standard).
  3. When indentation returns to the outer indentation level, the block terminates automatically.
๐Ÿ’ป Example 1: Indentation Defining if-else Blocks
# Check voting eligibility based on age
age = 20

if age >= 18:
    # 4 spaces indentation marks the IF block:
    print("Eligible to vote! โœ…")
    print("Please cast your vote responsibly.")
else:
    # 4 spaces indentation marks the ELSE block:
    print("Not eligible yet.")
    print("You must be 18 or older.")

# 0 spaces indentation: Executes unconditionally outside the if-else block
print("Verification check completed.")
๐Ÿ” Indentation Mechanics:
  • Lines 6-7 are indented with 4 spaces under if age >= 18: and execute ONLY when the condition is True.
  • Lines 10-11 are indented under else:, executing ONLY when the condition is False.
  • Line 14 has zero leading spaces, so it executes every time after the if-else finishes.
2Single-Line & Inline Comments (#)

Comments are explanatory annotations written by programmers to document code logic. The Python compiler completely strips comments during lexical analysis, resulting in zero memory or runtime performance cost.

In Python, single-line comments begin with the hash symbol (#). They can occupy their own line or follow a statement inline (separated by at least two spaces according to PEP 8):

๐Ÿ’ป Example 2: Single-Line and Inline Comments
# Step 1: Define pricing parameters
item_price = 45.00   # Price per unit in rupees
quantity = 3         # Number of items ordered
tax_rate = 0.05      # 5% GST tax rate

# Step 2: Calculate total amount including tax
subtotal = item_price * quantity
tax_amount = subtotal * tax_rate
final_total = subtotal + tax_amount

# Step 3: Display results
print("Subtotal: Rs.", subtotal)
print("Tax (5%): Rs.", tax_amount)
print("Final Total Bill: Rs.", round(final_total, 2))
๐Ÿ” Commenting Best Practices:

Write comments to explain WHY non-obvious business logic exists, not merely WHAT the code does. Good code is self-documenting for simple operations.

3Multi-Line Statements & Implicit Parentheses Continuation

According to the PEP 8 style guide, code lines should be limited to 79-99 characters for readability. The safest and most Pythonic way to wrap long expressions across multiple lines is by enclosing them in parentheses (), which activates implicit line continuation:

๐Ÿ’ป Example 3: Multi-Line Statement with Implicit Parentheses
# Calculate total score across multiple academic subjects
# Parentheses () allow clean multi-line continuation without syntax errors:
total_score = (
    85     # Mathematics score
    + 92   # Physics score
    + 78   # Chemistry score
    - 5    # Late homework penalty
)

print("Final Calculated Total Score:", total_score)
๐Ÿ” Why avoid backslashes (\)?

While Python allows explicit line continuation with a backslash \, backslashes are fragile: any trailing invisible space after the backslash causes a fatal SyntaxError: unexpected character after line continuation character. Parentheses (), brackets [], and braces {} are 100% safe.

4Functions and PEP 257 Docstrings (.__doc__)

A docstring (documentation string) is a string literal enclosed in triple quotes ("""...""") placed as the very first statement inside a function, class, or module.

Unlike regular # comments that disappear at compile time, docstrings are preserved in memory at runtime and can be inspected via the .__doc__ attribute or the built-in help() system:

๐Ÿ’ป Example 4: Defining and Inspecting Function Docstrings
def calculate_rectangle_area(length, width):
    """
    Calculate and return the area of a rectangle.
    
    Parameters:
        length (float): The length of the rectangle
        width (float): The width of the rectangle
        
    Returns:
        float: Calculated area (length * width)
    """
    return length * width

# Call function
area = calculate_rectangle_area(10, 5)
print("Calculated Area:", area)

# Inspect docstring at runtime
print("\n--- Function Docstring (.__doc__) ---")
print(calculate_rectangle_area.__doc__)
๐Ÿ” Why Docstrings are Vital:
  • Modern IDEs (VS Code, PyCharm) pop up docstrings as interactive tooltips during code completion.
  • Automated documentation generators (Sphinx, MkDocs) extract docstrings to build professional API documentation websites.
โš ๏ธ Common Developer Pitfall: Mixing Tabs and Spaces (TabError)

Mixing physical Tab characters and Space characters in the same source file causes TabError: inconsistent use of tabs and spaces in indentation. Always configure your code editor to insert 4 spaces when pressing the Tab key.

๐Ÿ’ป Hands-on Interactive Practice Challenge

Fix indentation and run the code to verify if weather is warm or cool.

Python 3 Practice Challenge โ–ถ Run in Compiler
temperature = 32

if temperature > 25:
    print("It is a warm and sunny day! โ˜€๏ธ")
    print("Drink plenty of water.")
else:
    print("It is a cool day! ๐Ÿงฅ")
Run This Challenge in Online Python IDE โ†’
โ“ Frequently Asked Questions (FAQ)

Q Can I use 2 spaces instead of 4 spaces for indentation?

The Python interpreter will execute code indented with 2 spaces as long as it is consistent within each block. However, PEP 8 strictly mandates 4 spaces across all professional Python codebases worldwide.

Q What is the difference between a comment (#) and a docstring (""")?

Standard comments (#) are stripped by the compiler and discarded. Docstrings (""") are preserved as executable string objects attached to the __doc__ attribute of functions, classes, and modules.

Q What happens if I forget indentation after an if statement or function definition?

Python immediately raises an IndentationError: expected an indented block before any code can execute.

OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Python 3.12+ runtime ยท Last updated August 2026