Using comments in Python code
Coding with Python
🕑 This lesson will take about 5 minutes
Comments are remarks that can be added to your code. Comments are only visible in your source code and are not processed as instructions when the program runs. Comments are useful as they can explain the purpose of a section of code, the purpose of a variable or function in the code, or notes about who wrote the code, when it was last updated, any external modules required to run the code, and the license. Comments can also be used to add notes/memos such as reminders to fix a problem during development (these comments can be removed when the code is published).
Comments are very useful during debugging and maintenance as they can make the code easier to understand (particularly for other people within a team who may not have written the original code) and can also make it easier to locate sections of code that might be responsible for an error.
It is important that you write your code in a way that is clear, makes sense, and speaks for itself. Code should not include a large number of comments but they definitely can be useful. Sometimes comments can provide context and help other developers quickly get an understanding of another developer's code. But don’t overdo it (use comments in moderation).
So how do you write comments in Python code?
If you are writing a comment that will occupy just one line of your code, then you begin the comment with a # character, for example:
# this is a single-line comment
If you are writing a comment that will occupy multiple lines in your code, then you begin the comment with ''' and end the comment with ''' too, for example:
''' this
is
a
multi-line
comment
'''
These comments will be ignored when the program runs and are only visible inside the source code. From here on in this course, you might find comments in the example code provided, explaining parts of the code eg. expected output.
Sample code
Next lesson: Numbers and math in Python