Comments are sections of text that are not read and interpreted by the computer.
Commenting code serves 3 major purposes:
Documentation
Who wrote this program? Why? When?
Explaining Code Functionality
What does this chunk of code do? How does it work?
This is only necessary when the what and how are not easily apparent to a programmer.
Turning code off
It is sometimes useful during testing and debugging to "turn off" lines or sections of code without deleting them. This can be done by turning them into comments. The code can later be uncommented to restore the code.
To write single-line comments, use # in front of the line you'd like to be a comment.
You can also use triple quotes (either ''' or """) to open and close a multi-line comment.
For example:
'''
This is a multi-line comment.
It explains the different types of comments.
Written by Carter McClung, 2021
'''
print("Hello!")
#This is a single-line comment. The next line is "commented out" and won't run!
#print("Programming is hard!")
print("Programming is fun!") #You can also put a comment on a line after your code
It is much better to write your code in an understandable way rather than having to write comments to explain it. Writing comments to explain your code or variable names can be bad because if you change your code, but forget to update your comments, your comments now don't reflect what your code actually does.
"A comment is a lie waiting to happen" - Josh Susser
So, when you can, make your code be self-explanatory by using good variable names and clean code rather than explaining with comments.