Introduction π
Comments are notes you write inside your code for yourself or other developers. Python ignores comments while running the program, meaning they donβt affect the output.
Note
1. What Are Comments? π€
Comments are used to explain what the code does. They are extremely helpful when revisiting your code after weeks or when working in teams.
basic_comment.py
# This is a comment
print("Hello Python!") # This prints a message2. Single-Line Comments (#) βοΈ
The # symbol starts a comment. Everything after it on that line is ignored.
single_line_comment.py
# This is a single-line comment
x = 10 # Inline comment
print(x)Note
3. Multi-Line Comments (""" """) π
Python doesn't have true multi-line comment syntax, but developers use triple-quoted strings to create block comments.
multi_line_comment.py
"""
This is a multi-line comment.
You can write explanations here.
Python ignores this as long as it is not assigned to a variable.
"""
print("Learning Python Comments!")Note
4. Inline Comments π
Inline comments appear on the same line as code β useful for short explanations.
inline_comment.py
speed = 80 # speed in km/h
print(speed)5. Docstrings (Documentation Strings) π
Docstrings describe functions, classes, and modules. These are written using triple quotes inside the definition and can be accessed with help().
docstring_example.py
def add(a, b):
"""This function adds two numbers and returns the result."""
return a + b
print(add(10, 20))
help(add)Note
6. Why Use Comments? π―
- Explain complex logic
- Make code readable for teammates
- Help future you understand old code
- Describe function usage (via docstrings)
7. When NOT to Use Comments π«
Comments should not replace clean code. Avoid:
- Writing comments for obvious lines (e.g., x = 5 # set x to 5)
- Using long paragraphs β keep comments short and meaningful
- Outdated or incorrect comments β they cause confusion
Note
8. Real-World Example π§ͺ
real_world_example.py
# Ask user for their name
name = input("Enter your name: ")
# Greet the user
print(f"Hello, {name}!")
def calculate_discount(price):
"""
This function calculates a 10% discount
and returns the final amount.
"""
return price - (price * 0.1)
print(calculate_discount(100))Conclusion π
You now know how to use comments to make your Python code clean and professional. Want the next lesson on Operators, Expressions, Conditional Statements, Loops, or Functions? Just tell me! π