trylineTryline homeF1 · First steps
About 4 minutes

Comments

Leave notes in your code for people, and switch a line off without deleting it.

1. Notes for people

Sometimes you want to leave a note in your code. For yourself next week, or for someone else reading it. That's a comment.

# say hello to the user
print("Namaste")
OUTPUT
Namaste
#A hash starts a comment: a note Python skips.
say hello to the userThe note itself. Python skips the rest of that line completely.

So when we run this, only Namaste appears. The note is for people, not for Python.

2. At the end of a line

A comment can also sit at the end of a line of code. Python runs the code part, and skips everything from the hash onwards.

city = "Amsterdam"  # where the user lives
print(city)
OUTPUT
Amsterdam

3. Switching a line off

You can also switch a line off. Put a hash at the start of a line, and Python skips that line. Programmers call this commenting it out.

print("Latte")
# print("Muffin")
print("Cake")
OUTPUT
Latte
Cake

Only Latte and Cake appear. The muffin line is still there, just switched off. Remove the hash, and it's back.

TRY IT: SWITCH A DIFFERENT LINE OFF, THEN RUN
OUTPUT
Press Run
What does this show? print("Chai") then # print("Samosa") then print("Vada")

4. One thing to watch

A hash inside quotes is not a comment. It's just part of the text. Inside quotes, Python treats everything as text.

print("Order #42 is ready")
OUTPUT
Order #42 is ready

5. Good comments

A good comment explains why, not what. Writing 'print namaste' above a print line tells nobody anything. But 'greet the user before asking their name' explains the reason.

Which is the better comment?

6. Where it's used

In real teams, comments help the next person understand the code fast. And when you're testing, switching lines off with a hash is something you'll do every day.

Explaining code to teammatesSwitching lines off while testing
Ready for your missionKettle & Crumb: "The screen shows the word special instead of today's special!"
Start the mission
Was this page clear?