Python Comments and Indentation
"Code is read much more often than it is written." - Guido van Rossum (Creator of Python)
To write professional Python, you must master two critical tools: Comments (which explain logic) and Indentation (which defines structure).
Python Comments
A comment is a text note written directly in your code that the computer ignores. It allows you to document your logic without affecting the program execution.
1. Single-Line Comments
A single-line comment is a note that occupies only one line of text. It is used to explain the code immediately following it.
Syntax: Type the hash symbol (#). Python ignores everything after this symbol on that specific line.
# This is a single-line comment
print("Hello World")
2. Inline Comments
An inline comment is a short note placed on the exact same line as a code statement.
Syntax: Type the code statement, add at least two spaces, then type the hash symbol (#) followed by your note.
x = 5 # This is an inline comment
Exercise 1: Annotating Logic
The code below calculates a price, but the context is missing. Add two comments:
- A Single-Line Comment above the math explaining the business rule ("Apply Holiday Discount").
- An Inline Comment next to the variable explaining the value ("15% rate").
# Apply Holiday Discount
rate = 0.15 # 15% rate
price = 200
final_price = price - (price * rate)
print(final_price)
Your output will appear here...
3. Docstrings (Documentation Strings)
A Docstring is a multi-line string used to document a specific segment of code, such as a function or a class. Unlike standard comments, Docstrings are retained by Python at runtime.
Syntax: Enclose the text in triple quotes ("""). This must be the very first line inside the function.
Exercise 2: Writing a Docstring
The function below has no documentation. Wrap the description text in triple quotes to create a valid Docstring.
def calculate_area(radius):
"""
Calculates the area of a circle.
Takes radius as an argument.
Returns the area value.
"""
pi = 3.14
return pi * (radius ** 2)
print(calculate_area(5))
Your output will appear here...
Want to master Python fundamentals? This lesson is part of our Free Python course covering variables, data types, functions, and more.
Explore this free Python course ->Indentation and Structure
In many programming languages, curly braces {} are used to group code. Python uses Indentation.
1. Indentation
Indentation is the empty whitespace at the beginning of a line of code.
It tells Python which lines of code belong to a specific block.
Syntax Rule: Use 4 spaces per indentation level.
2. Blocks and Scope
A "Block" is a group of statements that execute together. "Scope" refers to the context in which that block is valid.
Syntax Rule: Any statement ending in a colon (:) starts a new block. All subsequent lines indented by 4 spaces belong to that block.
Exercise 3: Defining a Block
The Logic: The "Access Granted" message should only print if the password is correct. It must be inside the if block.
Task: Indent the print statement by 4 spaces to move it inside the block.
password = "wrong_password"
if password == "secret_code":
# Inside the block (Indented)
print("Access Granted!")
# Outside the block (Un-indented)
print("Login attempt finished.")
Your output will appear here...
3. Nested Blocks
Nesting is the practice of placing one code block inside another code block (e.g., an if statement inside a for loop).
Syntax Rule: Increase indentation by 4 spaces for every new block depth.
- Level 0 (0 spaces): Main program.
- Level 1 (4 spaces): Inside the first block.
- Level 2 (8 spaces): Inside the second (nested) block.
Exercise 4: Structure Nested Logic
We need to filter a list of temperatures. Organize the code structure using correct indentation:
- The
ifstatement must be inside the Loop (Level 1). - The
printstatement must be inside the If check (Level 2).
temps = [102, 98, 105, 99]
for t in temps:
# Level 1: Inside the loop
if t > 100:
# Level 2: Inside the If
print(f"Warning: {t} is too high!")
Your output will appear here...
Progress Check: You have mastered the syntax. Now let's review the best practices.
Python ExerciseBest Practices Checklist
Before writing production code, verify your style against these standards.
| Practice | Explanation |
|---|---|
| Explain "Why", not "What" | Do not describe the syntax (the code shows that). Describe the business reason (why you are doing it). |
| Keep Comments Current | If you change the code logic, you must update the comment immediately to avoid confusion. |
| Strict Indentation | Always use 4 spaces. Do not mix tabs and spaces, as this causes errors in Python 3. |
Final Challenge: Refactoring Code
The code below is unreadable and lacks documentation.
Your Mission:
- Add a Docstring explaining the function's purpose.
- Indent the logic correctly inside the function and loop.
- Add one comment explaining the business logic of the
ifcheck.
def process_numbers(data):
"""
Calculates the sum of all positive numbers in a list.
"""
total = 0
for num in data:
# Business Logic: Only include positive numbers
if num > 0:
total += num
return total
result = process_numbers([10, -5, 20, -1])
print(f"Sum of positives: {result}")
Your output will appear here...
Lesson Completed
You now understand the definitions of Indentation and Scope, and how to use them to structure Python code.
Full Python Course
Master Python with 11+ hours of content, 50+ exercises, and real-world projects.
Enroll Now