Python provides several methods for inserting comments at the core of the code to provide additional information to help you better understand your code. A comment is simply text that will be ignored when the program is executed. Comments can be used to explain a complicated part of a program, or to put indications in the code, such as the source code, the version of the language or script or many other things.
In Python, there are two ways to annotate your code.
Python Comment Basics
In Python, we insert a single line comment with the # character (a hash sign).
# Comment : I like AppleS.
Using the hash sign to start the line tells the system to ignore everything on that line. You can still see this when you edit the file. When the application runs, it pretends that these lines do not exist. This can be very useful when you don’t want to forget what you’re doing with your code.
Here is an example with a program that asks my name and displays it:
# Ask for the name then display it print('Enter your name:') x = input() print('Hello, ' + x)
The system will only execute the code from the second line onwards. The first line explains what the other lines of code are supposed to do.
Output: Enter your name: AMIRADATA Hello, AMIRADATA
You can define any line as a comment and use as many as you like. If your code has different blocks, you can use a comment to explain each block:
# Ask for the name then display it print('Enter your name:') x = input() print('Hello, ' + x) # Ask the age and then display it print('Enter your age:') x = input() print("You're " +x+" years old !")
Output: Enter your name: AMIRADATA Hello, AMIRADATA Enter your age: 28 You're 28 years old !
Python multiline comment
In general, you should use the hash sign for each line to mark it as a comment. This is the most recommended method :
#This is a #multi-line #comment
However, there is a faster way to comment on a whole piece of code, which is to use a triple quotation mark to get a function similar to that of a comment :
""" This is a multiline comment You can insert all the information you need between these 3 quotation marks. """
This method is not actually a comment but defines a text constant of the text between the quotes. It is not displayed, but exists and could potentially cause unexpected errors. This method can be problematic because, in some circumstances, it creates a docstring. If you use the following triple quote:
- A function signature
- A class definition
- At the start of a module
I hope this tutorial has helped you better understand python comments. If you have any questions don’t hesitate to say so in comments!