HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to Python: Print and RepeatVariablesData Types & NumbersStringsListsConditions (if / elif / else)Loops (for / while)FunctionsOperatorsDictionariesTuples & SetsError Handling (try / except)Classes (Object-Oriented)File OperationsComments & IndentationBooleans (True / False)Lambda & map / filterModules (import)InheritanceVariable Scope
REFERENCE
📖 Overview
🖥️ Output & Input
🔢 Numbers & Math
✍️ String
📋 List
🗂️ Dictionary & Set
🔁 Condition & Loop
🧩 Function
📁 File & Error
🔄 Type & Conversion
Python›Comments & Indentation

Comments & Indentation

Comment lines with #, and Python's most critical rule: indentation (whitespace) defines blocks.

Simple enough for a 5-year-old to understand

Comment line: #

Everything starting with # is a comment; Python doesn't run it. It's used to note what the code does.

Comment example
1
# This is a comment, it does not run
Everything after # is ignored.
CommentEverything after # is ignored.
2
print("Hello") # it also works at the end of the line
A comment can also be written after code.
Output / InputA comment can also be written after code.
CommentOutput / Input
💡 Hint: Comments are for explaining "why" you did something; they're also used to temporarily disable code.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (2 left)

1.In Python, what goes at the start of a line to make it a comment?
2.Write a comment line, then print "Working code" (the comment should not appear in the output).

🎯 Expected output: Working code

Loading editor…

About this topic

Comments are lines that Python doesn't execute but people read. A good comment explains WHY the code does something, not WHAT it does: the code itself already tells you what it does, but only a comment can explain why that strange-looking check is there.

Indentation in Python, unlike comments, is not optional — it is part of the language's syntax. In other languages, indentation is for readability; in Python, it determines where blocks begin and end. Incorrect indentation produces a program that doesn't run, or worse, runs incorrectly.

What you will learn

  • Writing single-line comments
  • Using multi-line explanations and docstrings
  • How indentation determines block scope
  • Why the 4-space convention is followed
  • The consequence of mixing tabs and spaces

When to use?

Write a comment for a decision that isn't clear from the code: the reason for a workaround, where a magic number comes from, why a sorting order is important. Writing a docstring at the beginning of functions is the standard way to document what it does, its parameters, and what it returns.

Writing a comment on every line is harmful: when the code changes, comments aren't updated, and a comment that gives incorrect information is worse than having no comment at all.

Common mistakes

Wrong

def check(x):
    if x > 0:
        return True
      return False

The indentation of the last line is inconsistent with the others. Python raises "IndentationError: unindent does not match any outer indentation level" because it cannot determine which block this line belongs to.

Correct

def check(x):
    if x > 0:
        return True
    return False

Wrong

total = 0
for n in [1, 2, 3]:
    total += n
    print(total)

Since the print line is INSIDE the loop, it runs on every iteration and outputs three lines. If you only want the final total, you need to unindent by one level. You won't get an error message; the code will silently do what you didn't want.

Correct

total = 0
for n in [1, 2, 3]:
    total += n
print(total)

Wrong

# this function takes x and adds 1
def inc(x):
    return x + 1

The comment just repeats the code itself; it adds no information. To document what a function does, a docstring should be used instead of a comment, and a comment should only be written for something that isn't obvious from the code.

Correct

def inc(x):
    """Increments the given number by one."""
    return x + 1

Frequently asked questions

How many spaces of indentation should I use?

4 spaces. Python technically accepts any number as long as it is consistent, but the official style guide PEP 8 recommends four spaces, and almost all Python projects follow this. Configuring your editor to press 4 spaces on the tab key is the most practical solution.

Tabs or spaces?

Spaces. Mixing the two in the same file leads to the "TabError: inconsistent use of tabs and spaces in indentation" error, which is annoying to find since it is not visible to the naked eye. When editing someone else's code, enabling your editor to show invisible characters will make your job easier.

How do you write a multi-line comment?

Python does not have a separate multi-line comment syntax; a hash symbol is placed at the beginning of each line. Triple-quoted strings technically work, but they are actually string literals, not comments; therefore, they should only be used as docstrings at the beginning of functions and classes.

Summary

Comments are for explaining the why, while docstrings are for documenting the function. Indentation in Python is not about aesthetics, it is syntax: using 4 spaces and not mixing tabs and spaces are mandatory habits.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code