Notes for humans that Python skips: # comments and triple-quoted strings.
# this is a single line comment
x = 5
# ans: another comment
y = 10
Everything after # on a line is ignored. The run shows which lines Python actually executes.
# comment after code
x = 5 # inline comment
name = "Alice" # another inline
The code before the # runs; the rest of the line is a note.
# comment after code
x = 5 # inline comment
name = "Alice" # another inline
# comment after code
x = 5 # inline comment
name = "Alice" # another inline
"""
This is a
multi-line comment
or docstring
"""
x = 5
Strictly, this is a string that is never stored anywhere, so it has no effect. At the top of a function it becomes the docstring.
'''
This is also
a multi-line comment
'''
y = 10
Three single quotes work exactly like three double quotes.
# x = 10
x = 5
# ans: x is 5 (commented line ignored)
Putting # in front of a line "comments it out": a handy way to switch code off.
Decide what runs and what doesn't, then press →.
# what is x?
# ans: x = 10
x = 5
# ans: 5
# what gets executed?
x = 5 # x = 10
# ans: x is 5
# multiline comment?
"""
x = 10
"""
x = 5
# ans: x is 5
# can you do this?
x = 5 """comment"""
# ans: SyntaxError
# what about this?
x = 5 # comment
y = x
# ans: y is 5
# nested comments?
# ans: # this is a comment
# ans: valid, just a comment
# multiline string as comment?
'''
This is also
a comment
'''
# ans: valid if not assigned to anything
# what is x?
x = 5
# ans: x = 10
# ans: x is 5
# inline multiline?
x = 5 """ this won't work """
# ans: SyntaxError
# comment with backslash?
x = 5 # this is \
# ans: a comment
# ans: two separate single-line comments
A backslash cannot continue a comment onto the next line; every comment line needs its own #.
# doc string vs comment?
def func():
"""This is docstring"""
# This is comment
pass
# ans: both valid, different purposes
The docstring is kept (try help(func)); the # comment is thrown away.
# to end of lineEverything after # is ignored, whether on its own line or after code.
A string on its own is evaluated and thrown away, so it works as a multi-line comment.
A string first thing in a function documents it.
x = 5 """text""" is a SyntaxError; only # can follow code.