- Home
- /
- Python Comments
Python Tutorial
Introduction
Python Data Types & Oper...
Python Strings
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Conditional Statements
Python Loops
Python Functions
Python Modules
Python OOPS
Advanced Topics
File Handling
- Home
- /
- Python Comments
Python Comments
When writing code, not everything is meant for the computer to execute. Sometimes, as developers, we want to leave notes for ourselves or others, or temporarily skip certain lines during testing. That’s where comments come in.
In Python, comments are completely ignored by the interpreter. Their purpose is to explain the code or prevent execution of specific lines without deleting them.
Single-Line Comments
To create a single-line comment, simply begin the line with a #
symbol. Everything after #
on that line will be treated as a comment.
# This is a single-line comment
print("This is a print statement.")
Output:
This is a print statement.
You can also place a comment at the end of a line of code:
print("Hello World") # This prints a greeting
Output:
Hello World
You can even comment out a full line of code during testing:
print("Python Program")
# print("This line is skipped by Python")
Output:
Python Program
Multi-Line Comments
Python doesn’t have a dedicated syntax for multi-line comments like some other languages do. But we can still achieve multi-line commenting in two ways:
1. Using # on every line:
# This block explains what the following code does.
# It checks if a number is greater than 5
# and prints the result accordingly.
p = 7
if p > 5:
print("p is greater than 5.")
else:
print("p is not greater than 5.")
Output:
p is greater than 5.
2. Using triple quotes """ """ or ''' '''
Technically, this is a multi-line string, but if it’s not assigned to a variable or used in any expression, it behaves like a comment.
"""
This example checks if a number is greater than 5.
This is not executed, just stored as a multi-line string.
"""
p = 7
if p > 5:
print("p is greater than 5.")
else:
print("p is not greater than 5.")
Output:
p is greater than 5.
Why Use Comments?
To explain complicated code blocks
To disable specific lines during debugging
To make code easier to understand for others (or your future self!)
Final Notes
While comments are ignored during execution, they are a crucial part of clean, maintainable code. Write them meaningfully, and keep your explanations short and relevant.