Python Syntax, Indentation & Comments
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:
- A colon
:signals the start of a new indented code block (afterif,elif,else,for,while,def,class,try,with). - Every line within that block must be indented by exactly 4 spaces (the official PEP 8 standard).
- When indentation returns to the outer indentation level, the block terminates automatically.
# 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.")
- 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.
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):
# 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))
Write comments to explain WHY non-obvious business logic exists, not merely WHAT the code does. Good code is self-documenting for simple operations.
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:
# 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)
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.
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:
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__)
- 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.
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.
Fix indentation and run the code to verify if weather is warm or cool.
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! ๐งฅ")
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.