If you have opened a Python file and noticed lines starting with the # symbol, you were looking at comments. The # character — commonly called a hash, number sign, or pound sign — is Python's single mechanism for marking text that the interpreter should skip entirely. This tutorial walks through every way the # symbol is used in Python, from simple notes to special directives the interpreter reads before running your code.
When the Python interpreter reads a .py file, it processes each line from top to bottom. The moment it encounters a # character that is not inside a string literal, it discards everything from that # to the end of the line. The discarded text never becomes part of the compiled bytecode, so comments cost nothing at runtime. They exist only in your source code for humans to read.
The # Symbol Creates a Comment
A comment is a piece of text that exists in source code solely for the benefit of the person reading it. Python's interpreter pretends the text is not there. Other programming languages use symbols like // or /* */ for comments, but Python relies exclusively on the # character. There is no alternative comment syntax built into the language.
# This entire line is a comment
print("Hello, world") # This part after the code is also a comment
When you run the code above, the output is simply Hello, world. Python ignores the # text on both lines. The first line is skipped entirely, and on the second line, only the print() call is executed.
A # inside a string literal is just a regular character and does not start a comment. Writing print("Use # for comments") prints the # as part of the output.
Comments serve several practical purposes. They explain why a particular approach was chosen, mark sections of code that need future revision, temporarily disable lines during debugging, and provide context that variable names alone cannot convey. Well-written comments make a codebase easier to maintain, especially when you return to your own code after weeks or months away from it.
Three Kinds of # Comments
Python programmers use the # symbol in three distinct patterns. Each follows the same core rule — everything after # on a line is ignored — but the placement and intent differ.
Single-line comments
A single-line comment occupies an entire line by itself. The # appears at the beginning of the line (after any indentation), and the rest of the line contains your explanatory text. This is the form you will write and read more than any other.
# Calculate the total price including sales tax
tax_rate = 0.0825
total = price + (price * tax_rate)
Inline comments
An inline comment appears on the same line as a statement, separated by at least two spaces. PEP 8, the official Python style guide, recommends using inline comments sparingly and only when the statement needs clarification that is not obvious from the code itself.
timeout = 30 # seconds before the connection drops
retries = 3 # max attempts before raising an error
Avoid stating the obvious in inline comments. Writing x = 10 # set x to 10 adds clutter without adding value. Save inline comments for information the code cannot express on its own, such as units of measurement, edge-case reasoning, or business logic references.
Block comments
A block comment is a group of consecutive single-line comments that together explain a section of code. Each line begins with # followed by a single space. If the explanation has multiple paragraphs, separate them with a line containing only a #.
# Validate the user's input before processing.
# If the value is not a positive integer, the
# function returns None and logs a warning.
#
# This check was added after ticket #4821
# exposed a crash when negative values reached
# the database layer.
def validate_input(value):
if not isinstance(value, int) or value < 0:
return None
return value
Block comments are the PEP 8-recommended way to write multi-line explanations. Python does not have a dedicated multi-line comment syntax like the /* */ found in C or Java. While triple-quoted strings (''' or """) are sometimes used as a shortcut, they are string literals, not true comments. PEP 8 recommends consecutive # lines for block comments.
- Placement
- On its own line, before the code it describes
- PEP 8 rule
- Indent to the same level as the code below it. Start with # followed by a single space.
- Placement
- On the same line as a statement, after at least two spaces
- PEP 8 rule
- Use sparingly. Should not state the obvious. Max 72 characters for comments.
- Placement
- Multiple consecutive lines, each starting with #, above the code block
- PEP 8 rule
- Each line starts with # and a single space. Separate paragraphs with a line containing only #.
Build a valid Python inline comment that prints a greeting and explains it:
Special Uses of the # Symbol
Beyond regular comments, the # character appears in two specialized directives that Python's parser treats differently from normal code. Both look like comments to the human eye, but they carry functional significance.
The shebang line
A shebang line begins with #! and must appear on the very first line of a script. It tells Unix-like operating systems (Linux and macOS) which interpreter to use when the script is executed directly from the terminal. The name "shebang" comes from combining the words "hash" and "bang" (the exclamation mark).
#!/usr/bin/env python3
# The shebang above lets you run this file with: ./script.py
# instead of: python3 script.py
print("Running directly from the terminal")
The operating system's kernel reads the #! sequence and uses the path that follows it to locate the interpreter. Python itself treats the shebang as an ordinary comment and ignores it. On Windows, the shebang has no effect because the OS uses file associations to determine the interpreter. PEP 394 recommends using #!/usr/bin/env python3 because env searches the system's PATH, which works correctly inside virtual environments.
The encoding declaration
An encoding declaration is a specially formatted comment placed on the first or second line of a file. It was introduced by PEP 263 and tells the Python parser which character encoding the source file uses.
# -*- coding: utf-8 -*-
# This declaration was common in Python 2 files.
# Python 3 defaults to UTF-8, so it is rarely
# needed in modern projects.
In Python 2, the default encoding was ASCII, and files containing non-ASCII characters (such as accented letters or CJK characters) would fail to parse without an explicit declaration. Python 3 changed the default to UTF-8, which can represent virtually every character in use worldwide. You will still see encoding declarations in older codebases, but new Python 3 projects almost never need them.
Do not confuse comments with docstrings. A docstring is a triple-quoted string placed as the first statement in a module, class, or function. Unlike comments, docstrings are preserved in the compiled bytecode and can be accessed at runtime through help() or the __doc__ attribute. Comments are stripped during parsing and are never accessible at runtime.
This script is supposed to print two lines, but one of the comment symbols is wrong. Find the line with the syntax error.
// with # on line 3. Python does not recognize // as a comment marker. In Python, // is the floor division operator, so using it at the start of a line with text after it causes a SyntaxError. The correct line is # Print a farewell.
How to Write Comments Using the # Symbol in Python
Follow these five steps to start writing clear, useful comments in your Python scripts.
-
Open a Python file in your editor
Open any
.pyfile in a code editor such as VS Code, PyCharm, or IDLE. You can also create a new file and save it with the.pyextension. -
Type the # symbol followed by a space and your note
On any line where you want to leave a note, type
#followed by a single space and then your comment text. For example:# This variable stores the user's age. Python will ignore everything after the#on that line. -
Add an inline comment after a statement
To comment on the same line as code, leave at least two spaces after the statement, then type
#followed by a space and your note. For example:age = 25 # user's age in years. Keep inline comments short and use them sparingly. -
Write a block comment across multiple lines
For longer explanations, start each consecutive line with
#followed by a space. Separate paragraphs with a line that contains only a#. This is the approach recommended by PEP 8 for block comments in Python. -
Run your script to confirm comments are ignored
Run the script using
python3 your_file.pyin a terminal. Verify that the output contains only the results of your executable code. Any text preceded by#should produce no output and have no effect on the program's behavior.
Python Learning Summary Points
- The
#symbol is Python's only comment character. Everything from#to the end of the line is ignored by the interpreter and never becomes part of the compiled bytecode. - Python supports three comment patterns: single-line comments on their own line, inline comments after a statement (with at least two spaces of separation), and block comments made of consecutive
#lines. - The
#also appears in the shebang line (#!/usr/bin/env python3) that tells Unix-like operating systems which interpreter to run, and in the PEP 263 encoding declaration (# -*- coding: utf-8 -*-) that specifies a file's character encoding. - PEP 8 recommends a maximum of 72 characters per comment line, always placing a single space after the
#, and using block comments (consecutive#lines) instead of triple-quoted strings for multi-line explanations. - Comments should explain why code exists or how a tricky piece of logic works. Avoid restating what the code already says. Write comments as you code rather than trying to add them later.
The # symbol is one of the first things you will use in Python, and it remains one of the most important throughout your entire career writing Python code. Good commenting habits established early will save time and reduce frustration whenever you revisit old projects or collaborate with other developers. Practice writing comments that explain the reasoning behind your decisions, and your future self will be grateful.
Frequently Asked Questions
The # (hash) symbol in Python marks the beginning of a comment. When the Python interpreter encounters a # character, it ignores everything from that point to the end of the line. This allows programmers to write notes and explanations inside their source code without affecting how the program runs.
Python does not have a dedicated multi-line comment syntax like the /* */ found in C or Java. To write comments that span multiple lines, you place a # at the beginning of each line. While triple-quoted strings are sometimes used as a workaround, they are technically string literals, not true comments, and PEP 8 recommends using consecutive # lines for block comments.
A comment starts with # and is completely ignored by the Python interpreter. A docstring is a triple-quoted string placed as the first statement in a module, class, or function. Unlike comments, docstrings are stored as the __doc__ attribute of the object and can be accessed at runtime through help() or the __doc__ property.
A shebang line is a special comment that begins with #! on the very first line of a Python script. It tells Unix-like operating systems (Linux, macOS) which interpreter to use when running the script directly from a terminal. A common example is #!/usr/bin/env python3. The shebang has no effect on Windows and is ignored when Python imports the file as a module.
PEP 8, the official Python style guide, recommends at least two spaces between a statement and an inline comment. The comment itself should start with a single # followed by one space before the text. For example: x = 10 # assign ten to x.
No. The Python interpreter strips comments during the parsing stage before any code is compiled to bytecode. Comments are never included in the resulting .pyc bytecode files, so they have zero impact on the runtime performance of your program.
PEP 8 recommends limiting all lines of code to 79 characters, but specifically suggests a maximum of 72 characters for inline comments and docstrings. If a comment exceeds that length, break it across multiple lines, each starting with a #.
An encoding declaration is a specially formatted comment, such as # -*- coding: utf-8 -*-, placed on the first or second line of a Python file. It was introduced by PEP 263 and tells the parser which character encoding the source file uses. In modern Python 3, the default encoding is already UTF-8, so this declaration is rarely needed unless you are working with a non-UTF-8 encoding.
No. Python does not recognize // or /* */ as comment syntax. Those styles belong to languages like JavaScript, C, C++, and Java. Using them in Python will cause a SyntaxError. The only comment character in Python is the # symbol.
In most Python IDEs and code editors, you can toggle comments on selected lines using Ctrl + / on Windows and Linux or Cmd + / on macOS. This shortcut works in editors like VS Code, PyCharm, Sublime Text, and others. It automatically adds or removes the # symbol at the beginning of each selected line.