Python Comments
Table of Contents + β
In the last lesson you learned Python Syntax Basics, the rules Python follows to read your code. Now here is the nice part. You can also write lines that Python skips on purpose. These are called comments. They are notes for humans, not for the computer.
π€ Why Do We Need Comments?
Read some code you wrote a month ago and you will feel the pain. You stare at it and think, βwhat was I trying to do here?β The code still runs fine. But the reason behind it is gone.
A comment is a note you leave inside your code to explain the reason behind it. Python ignores it when the program runs. So it never changes what your code does. It only helps the person reading it later. And that person is often you.
So comments solve a real problem. They keep the why right next to the code. Then nobody has to guess.
π§© What Is a Comment?
Think of a comment like a sticky note on a fridge. The fridge does not read it. The note is there for the people in the house. A comment works the same way. Python does not run it. It just sits there for the next person who opens the file.
In Python you make a comment with the hash symbol #. Everything after the # on that line is ignored by Python.
Here is the simplest comment. It sits on its own line, right above the code it describes.
# Greet the user when the app startsprint("Welcome to FreeCodingSchool!")Python sees the # and skips the whole first line. Then it runs the print() line as normal.
Output
Welcome to FreeCodingSchool!See, the comment never showed up in the output. It was only there to tell you what the next line is for.
π¬ A Comment at the End of a Line
You can also put a # at the end of a line of real code. This is called an inline comment. Python runs the code first. Then it ignores everything from the # onward.
This example sets a price and explains the number right beside it.
price = 499 # price in cents, before taxprint(price)Python runs price = 499. Then it hits the # and skips the rest of that line.
Output
499Keep inline comments short. They share the line with code. So a long note there gets hard to read.
π« Commenting Out Code
Here is a trick you will use a lot. Sometimes you do not want to delete a line. But you also do not want it to run right now. Maybe you are testing something. You can put a # in front of it to switch it off. This is called commenting out a line.
In this example the second print is switched off. So only the first one and the last one run.
print("This line runs")# print("This line is switched off for now")print("This line runs too")The middle line starts with #. So Python treats it as a note and skips it.
Output
This line runsThis line runs tooThis is handy when you are hunting a bug. You can switch lines off one by one. Then you can see which one causes the trouble. Later you remove the # to switch the line back on.
π Notes Across Several Lines
What if your note is long and one line is not enough? Python has no special multi-line comment symbol. You just start each line with its own #.
Here a few lines explain a small calculation before it happens.
# Work out the final bill for the order.# We add the item price and the delivery fee,# then show the total to the customer.total = 250 + 40print(total)Every line that explains the plan begins with #. So Python skips all of them and only runs the last two lines.
Output
290π§΅ The Triple-Quote String (Docstring)
You will often see a different style at the very top of a function or a file. It uses three quotes to wrap several lines of text.
This example puts a description at the start of a function.
def greet(name): """Say hello to a person by name.""" print(f"Hello, {name}!")
greet("Riya")That """...""" line is a docstring. It is a short description of what a function or file does. You write it right under the def line.
Output
Hello, Riya!Now here is the catch. A triple-quote text is not really a comment. It is a string, a piece of text Python actually creates in memory. Python lets it sit there without using it. So it acts like a note. The difference is that tools can read a docstring later to show help about your function. A plain # comment cannot do that.
Tip
Use # for quick notes inside your code. Use a triple-quote docstring at the top of a function or file to describe what it does. They look similar but they do different jobs.
π Good Comment vs Noisy Comment
A comment should explain the why, not repeat the obvious what. If the code already says what is happening, do not copy it in words. Tell the reader something the code cannot.
The first comment below is noise. The second one actually helps.
# β Avoid: this just repeats what the code clearly saystotal = price * 1.18 # multiply price by 1.18
# β
Good: this explains the reason behind the numbertotal = price * 1.18 # add 18% sales tax to the priceSee the difference? The first one tells you nothing new. The second one explains why the number is 1.18. You could not guess that from the code alone.
β οΈ Common Mistakes
A few small slips trip people up when they start using comments.
- Forgetting the
#. A note without a#is read as code, so Python will usually raise an error. - Explaining the obvious. A comment like
# add one to xnext tox = x + 1just adds noise. - Letting comments go stale. You change the code but forget the comment. Now it lies. A wrong comment is worse than none.
- Treating a triple-quote string as a true comment. It is text Python builds in memory. So do not drop huge blocks of it in the middle of your code to switch lines off. Use
#for that.
β Best Practices
These habits keep your comments helpful instead of annoying.
- Explain the why, not the what. Let the code show what it does.
- Keep comments short and in plain words.
- Update the comment whenever you change the code beside it.
- Use a docstring at the top of every function to say what it does.
- Use comments to switch lines off while testing, then clean them up afterwards.
π§© What Youβve Learned
β A comment is a note for humans that Python skips when it runs.
β
A single-line comment starts with #. It can sit on its own line or at the end of a line of code.
β
You can comment out a line with # to switch it off without deleting it.
β
For a long note, start each line with its own #, since Python has no special multi-line comment.
β A triple-quote docstring describes a function or file, but it is really a string, not a true comment.
β Good comments explain the why, not the obvious what.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What does Python do with a line that starts with #?
Why: A # turns the rest of the line into a comment, which Python ignores while running.
- 2
How do you write a note that spans several lines using comments?
Why: Python has no multi-line comment symbol, so you start each line with its own #.
- 3
What is the main reason to 'comment out' a line of code?
Why: Putting a # in front of a line switches it off temporarily, which is handy while testing.
- 4
Which statement about a triple-quote docstring is true?
Why: A docstring is technically a string Python builds in memory, and tools can read it to describe your function or file.
π Whatβs Next?
Now that your code can explain itself, the next step is learning the special words Python reserves for its own use. These are the ones you cannot use as names.