Python comments are used to create sections of code that are ignored. Comments are useful for notes or to temporarily disable the block of code. Comments are made in Python by adding
# before a single line or multiline string.
Comments are used to write down notes in your code that will be ignored by the compiler or interpreter. For example, if you are writing a complex procedure over a period of hours, you may want to write a few comments to keep track of what each line of code does so that you don’t lose track.
Writing comments is useful for a number of reasons. If you are working with a big Python program, commenting can help you keep track of what is going on; if you’re working on a team, commenting helps ensure everyone understands each other’s work. Every developer eventually encounters a situation where they must include comments when writing code.
But how do you comment on code in Python? Like every other programming language, Python supports commenting. In this guide, we’re going to break down the basics of Python comments and discuss how you can leave notes in your code effectively.
In Python, comments begin with a hash character (number sign) and a whitespace character. Here’s an example of single line comments in Python:
# This is a demo comment
When you run your program, this line will be ignored by the compiler. Comments are to be read by humans, rather than to be executed by the program itself.
Let’s say that you are writing a for loop, and you want to remind yourself how it works. You may want to write a few comments so that when you come back to look at your code later, you’ll understand why you wrote the code.
In a for loop, you may have comments that look like this:
# Define students variable as an array of strings students = ["Nathan", "Alyssa", "Matthew", "Malcolm", "Alexis", "Katie"] # Loop through each item in the students array and print out each name for s in students: print("Student Name: ", s)
In the above example, our comments help us understand the purpose of our code and keep track of what is going on.
Comments should be added at the same indent level as the code to which the comment is referring. For example, if you are writing about a line of code within an
if statement, you would indent your comment the same way you did with your code.
Let’s use an example to illustrate the indentation structure of comments in Python. In the below example, our program loops through two arrays and gives each student a
fail for their test depending on their numerical score:
# Define an array with student names students = ["Nathan", "Alyssa", "Matthew", "Malcolm", "Alexis", "Katie"] # Define an array with student grades numericalGrades = [55, 72, 64, 86, 86, 59] # Loop through every student in "students" array for s in range(0, len(students)): # Check if the student's numerical grade is equal to or above 60 if numericalGrades[s] >= 60: # Print a message saying the student has passed their test print(students[s], "passed their test.") else: # Print a message saying the student has failed their test print(students[s], "failed their test.")
In simple terms, this program takes a list of students and their grades, loops through the list of students, then checks if each one has passed or failed their test.
In the above example, you can see that we comment on the same indentation level as the line to which we are referring. When we are discussing our
if statement, for example, we have indented our comment as well as our code.
By writing these single line comments, our program is more readable both for the author of the code, and for anyone else who may read the code in the future.
Python Comments: Inline
Inline comments are written on the same line as a statement, after the code has been written. Here is the syntax for an inline comment:
print(students) # Print the variable "students"
Inline comments are useful if you need to explain complicated parts of the code. They are also useful if you think you may forget how a specific line of code works in the future, or if you are working in a team and need to make sure everyone understands a specific line.
Inline comments are used to either explain what a line of code is doing or why the line of code exists.
Unlike other types of comments, inline comments should be used occasionally and only when necessary for the reader.
Python Comments: Block
Block comments can be used to explain code that is either more complicated or whose purpose is not immediately obvious. You may use a block comment to explain a unique function that uses an external library, for example.
Block comments are multi-line comment in Python and apply to some or all of the code below them. Block comments, like any other comments, are also indented at the same level as the code the comment is discussing.
Here is an example of a multiline comment that explains a
# The sortStudents function will parse arguments via the "student" variable. The # function simply returns the length of each student's name. We reference the sortStudents # function in the sort() function later in the code, which iterates over each item in the # "students" array and executes our sortStudents function. def sortStudents(student): return len(student) students = ["Nathan", "Alyssa", "Matthew", "Malcolm", "Alexis", "Katie"] students.sort(key=sortStudents)
As you can see, our comment spans multiple lines and describes the purpose of the code written below it.
While some developers may understand this code, other programmers may be confused about how it works or why it has been written. Using a block comment is a great way to explain an entire procedure or any other code that whose purpose is not immediately obvious to a developer.
Python Comments During Testing
So far, we have said that comments are mainly useful to help increase the readability of your work. But there is another purpose for comments in Python: testing.
When you are testing code, you may want to remove certain lines of your code without necessarily deleting them from your program.
For example, you may be testing two different approaches to a problem, and you don’t want to delete either one until you have tried out both. Or maybe there is an error in your code, and you want to comment out a few lines so you can identify the cause of the error. Either way, commenting out code during testing can be useful.
Let’s take our above example of a program that checks student grades. This time, though, we have deliberately misspelled a variable name, which has yielded an error. Here is our code:
students = ["Nathan", "Alyssa", "Matthew", "Malcolm", "Alexis", "Katie"] numericalGrades = [55, 72, 64, 86, 86, 59] for s in range(0, len(students)): if numericalGrades[s] >= 60: print(students[ss], "passed their test.") else: print(students[s], "failed their test.")
The error our program has given us is as follows:
Traceback (most recent call last): File "main.py", line 8, in <module> print(students[ss], "passed their test.") NameError: name 'ss' is not defined
Now we know the error is on line 7, we can start debugging. To make sure our code otherwise works, we may want to comment out line 7 and insert a testing print function. Here’s an example:
... if numericalGrades[s] >= 60: print("test") # print(students[ss], "passed their test.") else: print(students[s], "failed their test.")
When we run our code,
test is printed where appropriate, and we get messages for students who have failed their tests. Now we know the problem lies in our print statement. As you can see, we have misspelled our
students[s] variable on line, 7 which has caused our program to crash.
Once we fix the error, our program works again!
While the above example was easy to diagnose, if you are dealing with more complex code, commenting out certain lines—or even whole sections—can be useful to help you identify the issue present in your program.
That’s how you comment in Python! Using comments, you are able to make your programs more readable for everyone, including yourself. Well-written comments can help you keep track of your code as you go and allow you to maintain a record that can be referred back to later if you are struggling to understand your code later on.
In this tutorial, we have explored how to write comments, inline comments, and block comments in Python. We also discussed how some developers write comments for testing. Now you can write comments like a Python expert!
Python is one of the most popular programming languages in the world. If you are curious about how learning Python can help you break into a career in tech, download the free Career Karma app today to find out more!