Python · Code Helpers
Comments
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Comments
Comments are a way to add notes to your code. They are not executed by the interpreter and are used to explain what the code does.
In Python, there are two ways to write comments:
- Single-line comments start with a hashtag (
#
) symbol and continue until the end of the line.
- Multi-line comments are enclosed in triple quotes (
"""
).
# This is a single-line comment
"""This is a multi-line comment
It can span multiple lines"""
Exercise 2 — Single-Line comment
Which line contains a correctly written single-line comment?
Options
• ```level = 100 # Level of the codemon```
• ```level = 100 // Level of the codemon```
• ```level = 100 /* Level of the codemon */```
• ```level = 100 '' Level of the codemon ''```
Hint : Remember: Single-line comments start with # and can be placed at the end of a line of code
Exercise 3 — Multi-line comment
Which is the correct way to write a multi-line comment in Python?
Options
• """This is a
multi-line comment"""
• ""This is a
multi-line comment""
• /*This is a
multi-line comment*/
• ''This is a
multi-line comment''
Hint : Remember: Multi-line comments are enclosed in triple quotes (""")
Exercise 4 — Writting good comments
Comments are a double edged sword. They can help you understand your code better, but they can also make it harder to read if overused or poorly written.
That's why it's important to write good code FIRST, and then good comments.
Here are some tips:
- Use comments to explain why you did something, not what you did.
- Keep your comments short and to the point.
- Avoid using comments to explain obvious things.
Exercise 5 — Good comments bad comments
Which is the better written comment for the code below?
Options
• # Add a level after winning a battle
• # Increment the level of the codemon by 1
• # Add + 1
• # Increase level
Hint : Remember: Comments should explain WHY something is done, not only WHAT is being done.
Back to the course