You can use comments to include non-executable text in your code, as a note or reminder to yourself.
Comments are ignored by the Python compiler when your code is compiled.
To write a comment in Python, simply put the hash character
# before your comment. Python ignores everything after the
# and up to the end of the line.
# this code prints "Hello, World!" print('Hello, World!')
When writing comments, indent them at the same level as the code immediately below them.
# Initialize a function def hello(): # Print "Hello, World!" to the screen print('Hello, World!')
You can place comments anywhere in your code, even inline with other code. Inline comments are used for quick annotation on small, specific code snippet.
x = 1 # assign numerical value to x y = x + 2 # assign the sum of x + 2 to y
Block comments don’t technically exist in Python. However, there are two simple ways to create block comments.
The first way is simply adding a
# for each line.
# below code will print # 'Hello, World!' to the screen print('Hello, World!')
The second way is wrapping your comment inside a set of triple quotes
""" below code will print 'Hello, World!' to the screen """ print('Hello, World!')
Although this gives you the multiline functionality, this isn’t technically a comment. It’s a bare string literal that is not assigned to any variable.
So, it’s not ignored by the interpreter in the same way that
# comment is. But, you can use them as comments without any problem.
Be careful while placing these multiline comments. Depending on where you place them in your code, they could turn into docstrings.