Comments and code order
🌍 In real life. Picture a recipe card with notes in the margin: "Ammu's tip: less sugar". The cook follows the steps in order, from the top of the card to the bottom. The margin notes help the reader understand, but they aren't steps; nobody "does" a margin note.
A Python program works the same way. The lines are the steps, run in order, and comments are the margin notes.
The idea in one sentence: Python runs your lines from top to bottom, one at a time, and skips everything from a # to the end of that line.
Its words:
- order (or sequence): the top-to-bottom path Python takes through your code
- comment: text after a
#, written for people; Python ignores it - blank line: an empty line, also ignored; it only makes code easier to read
Step by step:
- Python reads line 1. If it starts with
#, it skips it. - Otherwise it runs the line, then moves down to the next one.
- Changing the order of the lines changes the order of what happens.
How Python treats a #. From the # to the end of the line is a comment, so a comment can fill a whole line or sit at the end of a line of code. There's one exception: a # inside quotes is just a character in the text, not a comment.
Why write comments? Code says what happens; a good comment says why. You'll thank yourself next week when you come back to your code.
Comments are also a handy way to switch a line off without deleting it: put a # in front, and Python skips it. Remove the # to switch it back on.
# This program greets you
print("Hello!") # a comment can also go at the end of a line
# print("This line will NOT run")print("Step 1")
# print("Step 2")
print("Step 3")print("Ticket #1") # the first # is inside the quotesprint("Breakfast")
print("Lunch")
print("Dinner")Mistakes and edge cases.
- The wrong comment symbol. Some languages use
//. In Python,// a notegivesSyntaxError: invalid syntax. - The wrong order gives no error. If you print "Go to school" before "Wake up", Python happily does it. It can't know what you meant, so check the order yourself.
- Commenting out half a statement. If an instruction spans two lines, comment out both, or Python sees a broken piece.
- A comment that's no longer true. If you change the code, update the comment too. A wrong comment is worse than none.
Quiz
What does this print?
print("A") # print("B") print("C")What does Python do with a comment?
- Runs it twice
- Ignores it
- Shows it in the output
What does this print?
print("second") print("first")Which symbol starts a comment in Python?
- #
- //
- --
Which line causes a SyntaxError?
// say hello print("Hello")
Coding tasks
These lines are in the wrong order. Rearrange them so the output is:
Wake up Brush teeth Go to schoolThis program shows three lines, but we only want the first and the last. Don't delete anything: turn the middle line into a comment.