Lesson 6
Comments - notes for people
After this lesson: You'll add comments that Python skips to your code and learn to switch lines off with #.
Video
The video for this lesson is coming soon.
Explanation
Sometimes you want to leave a note in your code - for yourself or for a friend: what does this line do? Today you'll meet comments - text that Python simply skips. ๐
Comments - notes for people
A line that starts with # is a comment. Python skips it - it doesn't run it and prints nothing. Comments are notes for you or for a friend reading your code:
# Prints the match score
print("FC Bajtek", 3, "-", 1, "FC Python")
A comment can also go at the end of a line of code - everything from # to the end of the line is skipped.
Bajtek and the notes in the code ๐ฌ
Click Next to go step by step.
Code
๐ฅ๏ธ Screen
Kuba doesn't get it
Bajtek wrote a program about a match. Kuba looks at the code and scratches his head: what does this line do? Code is for the computer - it's not always easy for a person to understand.
Python skips comments
See that the arrow skips the comment lines - nothing is printed.
1# This is a comment2print("Hello")3# This one too4print("Python") # a comment at the end of the line
โComments in the middle of a program
Lines with # print nothing - the arrow just skips them.
1# This is a note for people2print("One")3# print("This won't appear")4print("Two") # a note at the end
โA smiley with instructions ๐
The comments say what each part does. The screen shows only the picture.
1# eyes2print(" o o")3# nose4print(" ^")5# smile6print(" ---")
โSwitching lines off
A # at the start "switches off" a line. Remove it and the line works again.
1print("On")2# print("Off")3print("Also on")
โ# in quotes is not a comment
Watch out, a trap! The # sign starts a comment only outside quotes. Inside quotes it's an ordinary character, like a letter:
print("Bajtek #1")
prints Bajtek #1 - with the hash.
A hash inside text and outside it
The first # is in quotes - it gets printed. The second # is outside the quotes - it starts a comment, so the text after it disappears.
1print("Bajtek #1")2print("Bajtek") # 1
โWhat does the program print?
print("Bajtek #2") # super
What are comments for?
- to describe what a piece of code does - in a week you'll forget yourself!
- to switch off a line for a moment without deleting it.
The judge only sees what the program prints - comments don't change the result.
Remember
#starts a comment - Python skips everything from#to the end of the line.- A comment can be on its own line or at the end of a line of code.
#in quotes is an ordinary character, not a comment.
Great! Now the tasks: add comments and switch off the lines you don't need. ๐
Tasks from the video
We solve them together in the video - pause it and try first on your own.
Practice tasks
Try to solve them without the video. Stuck? Every task has hints and an editorial.
Sign in to save your progress.