Comments
In this tutorial, we'll write comments that clarify the why behind your code.
Comments are notes in your code that Python ignores. They are for humans.
# This is a comment
print("This line runs")
The comment does not run. It helps explain the code.
Why Comments Exist
Code explains what happens. Comments should usually explain why something happens.
Good comment:
# Discount applies only during the summer sale
discount = 0.20
Less useful comment:
# Set discount to 0.20
discount = 0.20
The second comment repeats the code. The first comment adds context.
Inline Comments
You can place a comment after code:
total = price * 1.2 # Add 20% tax
Use inline comments sparingly. If a line becomes crowded, put the comment above the code instead.
Temporarily Disabling Code
Beginners often use comments to temporarily stop a line from running:
print("This runs")
# print("This does not run")
This is useful while testing, but remember to clean up old commented-out code later.
Multi-Line Notes
Python does not have a special multi-line comment syntax. You will sometimes see triple-quoted strings used as notes:
"""
This note spans several lines.
Python treats it as a string.
"""
For now, prefer # comments unless you have a specific reason.
Practice
Write a short program that calculates the cost of three tickets. Add comments explaining the price and the final calculation.