Logo OnlineCBT
PYTHON Tutorial
PYTHON · LESSON 4

Syntax, Indentation and Comments

Write valid Python blocks, use whitespace deliberately, and add comments that explain decisions rather than obvious code.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive
Updated: 26 Jul 2026


1. The Fundamental Design Philosophy of Python Syntax

In traditional computer languages like C, C++, C#, and Java, the structural hierarchy of source code is maintained using explicit syntax tokens—specifically, curly braces ({ }) to define code blocks and semicolons (;) to mark the end of execution statements.

Python takes a radically different approach known as off-side rule syntax. Designed by Guido van Rossum with visual readability as a core principle, Python eliminates visual noise like semicolons and curly braces. Instead, it relies on whitespace, line breaks, and strict indentation levels to structure programs. This design forces all Python code to look uniformly formatted, clean, and easy to maintain across large software engineering teams.

The Zen of Python (PEP 20): "Readability counts." Python's parser enforces syntactic rules that naturally result in clean, uncluttered code bases.

2. Python Statements and Line Structure

A statement is an instruction that the Python interpreter can execute. In Python, a statement normally ends at the physical end of a line. You do not need to append a semicolon (;) at the end of a line.

Single-Line Statements

By default, every line in a Python script contains a single executable statement:

# Standard single-line statements
first_name = "Alan"
last_name = "Turing"
full_name = first_name + " " + last_name
print(full_name)

Multi-Line Statements (Line Continuation)

When an expression or mathematical operation exceeds a comfortable reading length (PEP 8 recommends a maximum of 79 characters per line), you can split a single logical statement across multiple physical lines using two techniques:

A. Implicit Line Continuation (Preferred)

Python automatically joins lines split inside parentheses (), square brackets [], or curly braces {} without needing extra symbols.

# Implicit line continuation inside parentheses
total_salary = (
    base_salary
    + performance_bonus
    + health_allowance
    - tax_deductions
)

B. Explicit Line Continuation (Line Continuation Character)

If an expression is not inside brackets, you can use a backslash (\) at the end of a line to tell Python that the statement continues on the next line.

# Explicit line continuation using backslash \
total_salary = base_salary + \
               performance_bonus + \
               health_allowance - \
               tax_deductions
Warning: No characters or spaces can follow the backslash (\) symbol on the same line. Even a hidden space after a backslash triggers a SyntaxError: unexpected character after line continuation character.

Multiple Statements on a Single Line (Discouraged)

Python allows multiple statements on a single line separated by semicolons (;). However, this practice violates PEP 8 style guidelines and should generally be avoided:

# Bad Practice (Violates PEP 8):
x = 10; y = 20; print(x + y)

# Clean, PEP 8 Compliant Standard:
x = 10
y = 20
print(x + y)

3. Python Indentation: Rules and Execution Mechanics

Indentation in Python is not just a formatting preference to make code look nice—it is a mandatory syntax requirement. Indentation defines how statements are grouped into code blocks (such as inside functions, loops, and conditional statements).

How Code Blocks Are Formed

A block of code (also called a suite) starts with a line ending with a colon (:) and continues as long as subsequent lines maintain the same level of indentation (leading whitespace).

Comparative View: C++ / Java vs Python

Language Paradigm Block Definition Method Example Code Block Structure
C++ / Java / C# Explicit Curly Braces { } (Indentation ignored by compiler)
if (score > 50) {
    System.out.println("Pass");
}
Python Mandatory Indentation & Colon : (Enforced by Interpreter)
if score > 50:
    print("Pass")

Indentation Rules (PEP 8 Standards)

  • Standard Width: Always use 4 spaces per indentation level.
  • Spaces vs Tabs: Spaces are preferred over tabs. Never mix tabs and spaces in the same project.
  • Consistency: All statements within the same code block must share the exact same number of leading spaces.

4. Code Demonstrations: Indentation in Action

Let's look at how indentation works in real scripts using interactive compiler-style blocks.

Practice Box 1: Single-Level Block Structure

CONDITIONAL_BLOCK.PY
user_age = 20

if user_age >= 18:
    print("Access Granted.")
    print("User is an adult.")

print("System execution completed.")
OUTPUT
Access Granted.
User is an adult.
System execution completed.

Practice Box 2: Nested Code Blocks

NESTED_BLOCKS.PY
account_active = True
account_balance = 500
withdrawal_amount = 200

if account_active:
    print("Account Verification: Active")
    if account_balance >= withdrawal_amount:
        account_balance = account_balance - withdrawal_amount
        print("Transaction Successful!")
        print("Remaining Balance:", account_balance)
    else:
        print("Transaction Failed: Insufficient Funds.")
else:
    print("Account Inactive.")
OUTPUT
Account Verification: Active
Transaction Successful!
Remaining Balance: 300

5. Common Indentation Errors and Diagnostics

1. IndentationError: unexpected indent

Occurs when you add indentation spaces to a line that is not inside a block statement.

# Invalid Code:
print("Line 1")
    print("Line 2")  # Unexpected indentation here!

# Interpreter Output:
IndentationError: unexpected indent

2. IndentationError: expected an indented block

Occurs when a block statement ending with a colon (:) is not followed by an indented line.

# Invalid Code:
if True:
print("Missing Indentation")  # Should be indented by 4 spaces

# Interpreter Output:
IndentationError: expected an indented block after 'if' statement on line 1

3. TabError: inconsistent use of tabs and spaces in indentation

Occurs when a single file mixes tab characters and space characters for indentation.

# Interpreter Output:
TabError: inconsistent use of tabs and spaces in indentation
VS Code Configuration Tip: Configure VS Code to automatically convert tabs to spaces. Go to Settings → Search for "Insert Spaces" → Enable it, and set "Tab Size" to 4.

6. Comments in Python

Comments are explanatory notes written inside source code for human developers. The Python interpreter completely ignores comments during compilation and execution.

Why Write Comments?

  • Code Documentation: Explaining complex algorithm logic to teammates or your future self.
  • Debugging Aid: Temporarily disabling lines of code during development without deleting them.
  • Maintainability: Helping reviewers understand why a particular technical choice was made.

Types of Comments in Python

A. Single-Line Comments

Single-line comments begin with a hash symbol (#). Everything following the # on that line is ignored by Python.

# Calculate discount price based on tax rate
original_price = 100.0
tax_rate = 0.05  # 5% State Tax
final_price = original_price * (1 + tax_rate)  # Inline comment

B. Multi-Line Comments

Python does not have a unique multi-line comment syntax like C's /* ... */. There are two standard ways to write multi-line comments in Python:

1. Consecutive Single-Line Hash Tags (PEP 8 Standard):

# This algorithm calculates the net pay for an employee.
# It factors in tax withholding, medical insurance deductions,
# and performance bonus distributions.
# Updated for tax fiscal year 2026.

2. Unassigned Multi-line Triple-Quoted Strings (Docstrings):

Multi-line string literals created using triple quotes (""" or ''') that are not assigned to a variable act as comments because Python executes them as unassigned expressions and immediately discards them from memory.

"""
This is a multi-line comment block.
It uses triple double-quotes.
It spans across multiple lines cleanly.
"""

Docstrings (Documentation Strings)

When triple-quoted strings are placed immediately under a function, class, or module declaration, they become official Docstrings. Unlike normal comments, docstrings are preserved by Python and can be accessed dynamically using the __doc__ attribute or the help() built-in tool.

DOCSTRING_DEMO.PY
def calculate_area(width, height):
    """Calculates the area of a rectangle given width and height."""
    return width * height

# Print the documentation string dynamically
print(calculate_area.__doc__)
OUTPUT
Calculates the area of a rectangle given width and height.

7. PEP 8 Rules for Syntax, Indentation, and Comments

PEP 8 is Python's official style guide. Adhering to these rules makes your code clean, standard, and professional:

Style Attribute PEP 8 Standard Rule
Indentation Use exactly 4 spaces per indentation level. Do not mix tabs and spaces.
Maximum Line Length Limit all lines to a maximum of 79 characters. Docstrings/comments limit: 72 characters.
Blank Lines Surround top-level functions and class definitions with 2 blank lines.
Inline Comments Separate inline comments from code by at least 2 spaces. Start comments with # and a single space.
Comment Clarity Keep comments updated when code changes. Stale, inaccurate comments are worse than no comments at all.

8. Frequently Asked Interview Questions with Answers

Q1: How does Python enforce code blocks without curly braces?
Answer: Python uses off-side rule syntax based on indentation. A code block begins with a header line ending with a colon (:) and includes all subsequent lines that share the same level of leading whitespace. The block ends when a line returns to a previous indentation level.
Q2: Why is mixing tabs and spaces dangerous in Python scripts?
Answer: Tabs and spaces render differently depending on the code editor's tab-stop configuration (e.g., a tab might look like 4 spaces in VS Code but 8 spaces in a Linux terminal). This visual mismatch leads to TabError runtime exceptions when parsed by the interpreter.
Q3: What is the difference between a standard comment and a Docstring?
Answer: Standard comments (marked with #) are stripped out during bytecode compilation and are invisible at runtime. Docstrings (triple-quoted strings placed under functions/classes) are preserved by the compiler and attached to object metadata, making them accessible at runtime using object.__doc__ or help().
Q4: How do implicit and explicit line continuations work in Python?
Answer: Implicit continuation automatically joins expressions split across multiple lines inside parentheses (), brackets [], or braces {}. Explicit continuation requires placing a backslash (\) at the physical end of a line to instruct the interpreter that the statement continues on the next line.
Q5: What happens if an unassigned triple-quoted string is placed in the middle of a function body?
Answer: The interpreter parses it as a valid string literal, evaluates it, and immediately discards it from memory since it is unassigned. It acts effectively as a multi-line comment, though PEP 8 prefers using consecutive # lines for general code comments.

9. Homework & Practical Assignment

Task 1: Fixing Indentation Errors

Copy the broken code block below into a new VS Code file named fix_indentation.py, identify all syntax/indentation errors, fix them, and run the file:

# Broken code for assignment
temperature = 35

if temperature > 30:
print("It is a hot day!")
    print("Stay hydrated.")
  else:
print("Weather is pleasant.")

Task 2: Line Continuation and Math Script

Create a script named payroll.py inside your lesson_04 folder. Define five numerical variables representing employee allowances and deductions. Calculate net pay using implicit line continuation inside parentheses and print the final formatted result.

Task 3: Module Documentation with Docstrings

Create a script named math_helpers.py. Include a module-level docstring at the top of the file describing the script's purpose. Define a custom function with a docstring, and print its documentation string to the terminal using print(function_name.__doc__).


10. File & Workspace Directory Structure

Standardized Course Workspace Layout:

Organize your project directory to keep homework submissions clean and easily navigable:

python_mastery_course/
│
├── lesson_01/
│   └── homework_submission.md
│
├── lesson_02/
│   └── environment_setup_verification.txt
│
├── lesson_03/
│   ├── hello.py
│   └── bill.py
│
└── lesson_04/
    ├── conditional_block.py
    ├── nested_blocks.py
    ├── docstring_demo.py
    ├── fix_indentation.py
    ├── payroll.py
    └── math_helpers.py

11. What We Will Learn Next

Next Up: Lesson 5 — Variables, Names and Assignment

Now that you have mastered Python's structural rules, whitespace mechanics, and comments, we will explore how Python manages data in memory.

In the next lesson, we will cover:

  • Understanding Variables as dynamic references (pointers to objects in memory).
  • Identifier naming conventions and rules (Snake_case, reserved keywords, legal vs illegal names).
  • The dynamic assignment operator (=), multiple assignment (x, y = 10, 20), and chained assignment (a = b = c = 0).
  • Memory identity inspection using the id() function and object mutability concepts.

```

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat