Python Comments · Exercises
Beginner

Python Comments Exercises

4 exercises that build on the Python Comments lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A comment is text after a # that Python ignores, used to explain why code does something, leave reminders, or temporarily switch a line off. By the end you can write single-line, inline and block comments, comment out code while debugging, tell comments from docstrings, avoid the multi-line comment myth, and write comments that explain why instead of what. You will practise: Silence the debug lines; Which hashes are comments?; Fix the swallowed return; Strip the comment from a line.

0 / 4 completed

Python Comments practice exercises

1. Silence the debug lines

Write code Easy

The program prints two DEBUG lines that were useful while testing. Comment them out with # so the program prints only Total: 45. Keep the total variable.

Your code
prices = [10, 15, 20]
print("DEBUG prices:", prices)
total = sum(prices)
print("DEBUG total computed")
print("Total:", total)

2. Which hashes are comments?

Predict the output Easy

Some # characters start comments and some are just text inside strings. Type exactly what the program prints.

Read this code
code = "#42"  # a string, not a comment
# print("hidden")
print(code, "# ok")
print("Done")  # print("Done again")

3. Fix the swallowed return

Fix the bug Medium

average(numbers) should return the average of a list, but it returns None. A comment is hiding part of the code. Fix it without deleting the explanation.

Your code
def average(numbers):
    total = sum(numbers)  # add them up; return total / len(numbers)

print(average([2, 4, 6]))

4. Strip the comment from a line

Write code Hard

Write strip_comment(line) that returns a line of Python source without its comment and without trailing spaces. A # only starts a comment when it is not inside quotes (single or double). Examples: x = 5 # five becomes x = 5, and color = "#fff" # white becomes color = "#fff".

Your code
def strip_comment(line):
    # naive version: breaks when # is inside a string
    return line.split("#")[0].rstrip()

print(strip_comment("x = 5  # five"))

Next lessonPython Variables

More Python Comments examples · All Python exercises