As your programs become longer and more complicated, you should add notes within your code that describe your overall approach to the problem you’re solving.
A comment allows you to write notes and explain code within your programs.
Comments are used to explain code when the basic code itself isn't clear. They are basically statements or lines that are ignored by the python interpreters.
Including comments in programs makes code more readable for humans as it provides some explanation on some block or line of code.
Based on the purpose of your program, comments can serve as notes to yourself or Todos, or they can be written with the intention of other programmers being able to understand what your code is doing.
Usually, it is a good idea to write comments while you are writing or updating a program as it is easy to forget your thought process later on, and comments written later may be less useful in the long term.
Creating a Comment
Comments start with a
#, and Python will ignore them. Generally, comments will look something like this:
# This is a single line comment
Comments can also be placed at the end of a line:
print("Pythonstacks") # Inline comments are a nice way to explain a statement
Python doesn't provide a special way of implementing multi-line comments. Rather multi-line comments in python are achieved by using the multi-line string :
""" I am a Multi-line String but i am also used as a multi-line comment. Python Ignores all statements in this block. """ # this also could be # used to write some # multi-line comments # in python
As long as the string is not assigned to a variable, Python will read the code, but then ignore it.
Use Case - commenting out code
Sometimes, programmers will put a
# in front of a line of code to temporarily remove it while testing a program. This is called commenting out code, and it can be useful when you’re trying to figure out why a program doesn’t work. You can remove the
# later when you are ready to put the line back in.
def greet(name): greeting = "Hello" return name + greeting greet_john = greet('john') # print(greet_john) greet_join.upper()
Commenting in python code is a very good habit, you may not need now it but trust me, your future self and other programmers reading your code might need it to understand various sections of your code.
This is an especially good idea if your code is open-source or up on GitHub and other programmers are trying to contribute. Help them get started by guiding them through what you’ve already done.