Lesson 3
Discovering your Paths
Chapter 10: Commenting
Comments
When writing code, you are not only writing for the computer.
You are also communicating with people, namely you and other programmers looking at your code.
Therefore, it is good practice to leave comments in your code describing what you have done.
- For yourself in one year’s time: “What in the world was I trying to do here? Why did I write this
while
loop?” - For other programmers trying to understand for your code: “I cannot understand the code. What in the world does this do? How am I going to fix this bug? Who wrote this pile of mess?!”
- For your lecturer: “Ok, I cannot understand what you are trying to do. And you did not leave any comments. Sorry, zero marks.”
All comments will be ignored by the Python interpreter. It is meant for humans to read.
In Python, you use a hash sign #
to represent a comment. Anything after the #
will be ignored by Python.
# Here is a comment.
# Here is another comment.
# Here is a third comment.
x = 5 # And you can write inline comments anywhere. But use this sparingly.
if x == 5:
# You can have comments inside a block.
# You should indent these for better readability.
print("Good")
Commenting out codes
Another trick that programmers often do is to use #
to temporarily comment out codes.
This is useful when you want to test out your code with something new, but do not want to remove your previous code for the time being.
In the code below, maybe you want to quickly test that the code works for different values of x
. You might also want to check the value of x
inside the if
statement with a print statement, which you might not need later.
# x = 3
x = 5
if x < 5:
#x = x + 1
x = x + 2
#print(x)
Of course, I encourage you to remove such commented code once you have finalised your code. This ensures that your code is readable and not confusing.