Syntax and Comments
Master Python's clean structural rules, significant whitespace, comment etiquette, and PEP 8 style standards to write readable code from day one.
When Guido van Rossum created Python in 1989, his primary goal was readability. Most programming languages invented before Python borrowed syntax rules from C: using semicolons ; at the end of every line, curly braces {} to bundle code blocks, and arbitrary whitespace rules that allowed code to look compressed and cryptic.
Python took a radically different path. In Python, visual structure matches logical structure. Code looks like clean English prose.
You can see this philosophy directly inside Python itself. Open your terminal, start the Python REPL, and type import this. You will see The Zen of Python, which includes timeless engineering wisdom:
“Beautiful is better than ugly."
"Explicit is better than implicit."
"Simple is better than complex."
"Readability counts.”
1. Significant Indentation (The 4-Space Rule)
In other languages, indentation is purely cosmetic for human eyes—the computer ignores indentation completely and only cares about curly braces {}.
In Python, whitespace is significant. Indentation is part of the language’s grammar and tells Python which lines belong inside a conditional statement, a loop, or a function:
score = 85
if score >= 50:
# Everything indented by 4 spaces belongs inside this if-block
print("Congratulations!")
print("You passed the exam.")
# This line is not indented, so it runs regardless of the condition
print("Evaluation complete.")
Output:
Congratulations!
You passed the exam.
Evaluation complete.
The Rules of Indentation
- Always use 4 spaces per indentation level: This is the universal standard defined in Python’s official style guide (PEP 8).
- Never mix Tabs and Spaces: Mixing tabs and spaces creates invisible bugs because different editors display a tab character with different widths (some 2 spaces, some 4, some 8).
- Let your editor do the work: In VS Code, when you press the
Tabkey, VS Code automatically converts it into 4 individual space characters for you.
What Happens When Indentation is Wrong?
If your indentation is uneven or misaligned, Python will halt immediately during Stage 1 compilation (as explored in how-python-works) and raise an IndentationError:
# BROKEN CODE EXAMPLE:
print("Step 1")
print("Step 2") # IndentationError: unexpected indent
Whenever you see IndentationError in your terminal, check the line number indicated by the error and ensure your spaces line up perfectly.
2. Statements and Line Endings
In languages like C, Java, or JavaScript, every statement must end with a semicolon:
// JavaScript requires semicolons
let total = 500;
let tax = 0.08;
In Python, a statement simply ends when the line ends:
# Python: clean, no semicolons needed
total = 500
tax = 0.08
(Technically, Python permits semicolons to separate multiple statements on a single line like x = 1; y = 2, but this is considered unpythonic and is strongly discouraged in real-world code).
Multi-Line Statements
Sometimes a line of code is long and needs to wrap onto multiple lines for readability. The recommended Pythonic way to wrap lines is inside natural parentheses ( ... ):
# Clean multi-line statement using parentheses
total_cost = (
item_price
+ shipping_fee
+ state_tax
- promo_discount
)
3. Case Sensitivity
Python is strictly case-sensitive. That means uppercase and lowercase letters are treated as completely different entities:
# These are three distinct variables in memory:
user_age = 25
User_Age = 30
USER_AGE = 35
print(user_age) # 25
print(User_Age) # 30
print(USER_AGE) # 35
Similarly, Python’s built-in keywords must always be lowercase or match their exact casing. For instance, print works, but Print or PRINT will crash with a NameError. Boolean values are capitalized: True and False, not true and false.
4. Writing Comments: Single-Line and Inline
Comments are human notes written directly in your source code. The Python interpreter ignores comments completely—they exist solely for human readers (including your future self when revisiting code three months later).
Single-Line Comments
Any text on a line after a hash symbol (#) is a comment:
# Calculate the final price including delivery
shipping_cost = 4.99
product_price = 19.99
Inline Comments
You can place a comment at the end of a line of code. PEP 8 recommends separating an inline comment from the code by at least two spaces:
timeout_seconds = 30 # Standard HTTP request threshold
Multi-Line Comments & Docstrings
For long paragraphs or documentation at the top of a file, Python supports triple quotes (""" or '''):
"""
Order Processing Module
Author: Engineering Team
Version: 1.0.0
This script handles order validation, tax calculations,
and inventory updates.
"""
When placed right under a function or class definition, triple-quoted strings become official docstrings, which tools like VS Code display in hover tooltips.
5. The Golden Rule of Writing Comments
One of the most common beginner traps is writing comments that describe the obvious:
# BAD: Explaining WHAT the code is doing (obvious noise)
x = x + 1 # Add 1 to x
user = "Alex" # Set user to Alex
Instead, write comments that explain WHY you wrote the code the way you did:
# GOOD: Explaining the business context or WHY
retry_limit = 3 # Prevent IP blocking by third-party payment gateway
discount = 0.15 # Senior citizen promotional rate approved for Q4
6. PEP 8: The Python Style Guide
Every language has an official style standard. For Python, it is PEP 8 (Python Enhancement Proposal #8). Following PEP 8 ensures your code looks like it was written by an experienced professional:
| Rule | Recommended Standard | Example |
|---|---|---|
| Variables & Functions | snake_case (all lowercase, words separated by underscores) | user_first_name, calculate_total() |
| Constants | ALL_CAPS (for values that never change) | MAX_CONNECTIONS = 100, PI = 3.14159 |
| Classes | PascalCase (capitalize each word, no underscores) | UserProfile, DatabaseConnection |
| Operator Spacing | Exactly 1 space around assignment and operators | x = 5 + 2 (never x=5+2) |
| Line Length | Keep lines under 79–88 characters | Avoid endless horizontal scrolling |
To dive deeper into automated formatting and linting tools like Black and Ruff, check out code-quality.
Summary Checklist
- Indentation: Use 4 spaces per block level. Never mix tabs and spaces.
- Lines: No semicolons required at the end of lines.
- Case: Python is strictly case-sensitive (
age != Age). - Comments: Start with
#and explain why something is done, not merely what the syntax says. - Naming: Use
snake_casefor variables and functions.
Now that you know the grammar of the language, move to input-output to learn how to make your programs communicate with humans and read interactive input from the keyboard.