Python Comments Examples
Short, runnable programs that show python comments in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Comments lesson.
1File header and section comments
Short comments at the top and between steps make a script easy to scan.
# Monthly report: totals per category
# Author: Asha
# --- data ---
spending = {"rent": 900, "food": 320, "travel": 85}
# --- calculation ---
total = sum(spending.values())
# --- output ---
print("Total spent:", total)Expected outputTotal spent: 1305
2Inline comments for units
Units and business rules are things a name cannot always tell you.
speed = 72 # km per hour
time = 2.5 # hours
distance = speed * time # kilometres
print(distance)Expected output180.0
3Commenting out code to find a bug
Switch lines off one at a time to see which one causes the problem.
values = [4, 8, 15]
total = sum(values)
# values.append(100) # suspect: this made the total too large
average = total / len(values)
print(round(average, 2))Expected output9.0
4TODO and FIXME notes
Reminders stay in the code and can be found with your editor's search.
def apply_discount(price, code):
# TODO: read discount codes from a file
# FIXME: negative prices are not rejected yet
if code == "SAVE10":
return price * 0.9
return price
print(apply_discount(50, "SAVE10"))Expected output45.0
5Docstring versus comment
The docstring describes the function for users. The comment explains an implementation detail.
def to_celsius(fahrenheit):
"""Convert a Fahrenheit temperature to Celsius."""
# 32 is the freezing point of water in Fahrenheit
return round((fahrenheit - 32) * 5 / 9, 1)
print(to_celsius(212))
print(to_celsius.__doc__)Expected output100.0
Convert a Fahrenheit temperature to Celsius.
6A triple-quoted string is not a comment
This text is created and then thrown away. Python treats it as an unused string, which is why it should not replace real comments.
"""
This is only a string that is never used.
"""
print("The program still runs")
note = """This one is stored in a variable."""
print(len(note))Expected outputThe program still runs
33
Practise next
Python Comments exercises → Back to the lesson
Python Syntax examplesPython Variables examplesPython Strings examplesPython Functions examples