Comments are like secret notes in our Python language that the computer does not read. Comments make code more readable and help explain what certain parts of the code are doing. They are just for us and our friends, providing context and explanations that make our code easier to understand and maintain. There are two types of comments in Python: single-line comments and multi-line comments.
Single-line comments
Single-line comments are the most common type of comments in Python. They start with a hash symbol (#
). Everything following the #
on that line is part of the comment. These comments are useful for adding brief explanations or notes about the code immediately following them. For example:
In the above example, the first comment explains the purpose of the following line of code, while the second comment provides context about the print
statement. Single-line comments help make the code more readable by providing insights and clarifications that are immediately visible to anyone reading the code.
Multi-line comments
Technically, Python does not have a specific syntax for multi-line comments. However, a common practice is to use triple-quoted strings ('''
or """
) as block comments. While these are actually multi-line strings, they are often used to span comments across multiple lines. For example:
Using triple-quoted strings in this way allows you to include more extensive explanations and notes in your code. However, it's important to note that these are strings and not actual comments in the strict sense. As a result, they are not ignored by the Python interpreter in the same way single-line comments are, and they should be used cautiously to avoid unintended side effects.
Comment shortcut
In most code editors, you can use a keyboard shortcut to toggle commenting on or off for a line of code. On Mac, the shortcut is ⌘/
(command + forward slash). On Windows, it’s Ctrl + /
(control + forward slash). If you place the cursor in a line of code and use this shortcut, the editor will insert a #
at the beginning of the line, effectively commenting it out. This feature is particularly useful for quickly adding or removing comments during the debugging process or when you want to temporarily disable certain parts of your code without deleting them.
Quiz Question
Hint: Think about what purpose comments serve in code development. How do they contribute to the understanding and maintenance of a Python script?
The correct answer is B) To make the code more readable and explain its functionality