TNS
VOXPOP
As a JavaScript developer, what non-React tools do you use most often?
Angular
0%
Astro
0%
Svelte
0%
Vue.js
0%
Other
0%
I only use React
0%
I don't use JavaScript
0%
NEW! Try Stackie AI
Python / Software Development

How to Use Comments in Your Python Code (And Why You Should)

This tutorial shows how to add comments to Python code so other programmers can understand the original intent of the code.
Sep 15th, 2024 2:08pm by
Featued image for: How to Use Comments in Your Python Code (And Why You Should)
Feature image via Unsplash+.

I’ve been writing about Python for some time now, starting from the very simple first steps and migrating toward more complicated scenarios and code. If you’ve been following my humble musings, you’ve probably noticed one glaring issue with all of them: the lack of code comments.

There’s a reason I’ve demonstrated Python without comments: because it’s easier to read. This is especially so for those who are just taking their first steps with the language. When I first started to learn Python, I had to strip all the comments from the code because I found them too distracting. Once the comments were removed, I could see the code more clearly and make sense of what I was doing.

However, in the real world, code comments are essential.

Before I get into this, it’s important to understand the difference between comments and documentation. Back in 2006, Jeff Atwood described it perfectly in a blog titled “Code Tells You How, Comments Tell You Why.” Atwood also explains that the best kind of comments are the ones you don’t need because the goal is to create code as simple as possible to understand.

Note: We’ll talk about documenting code in a separate article.

That kind of leads us to what comments are. Essentially, they help the programmer understand what they’ve done in the code. Even better, comments help other programmers understand what the original intent of the code was. This is done on the off-chance that someone else has to take over a project or if it is done in a collaborative environment. If you’re working with several programmers on the same code and you don’t comment your work, one of the other programmers might not have the slightest idea what your code does or why it’s there.

That could lead to confusion (or worse).

You don’t want that.

Ergo … comments.

Remember, collaboration is a team effort, so you need to make sure that any other team member can take up your code and continue the work without having you explain it to them first.

That’s the why of it all. But what about the how?

Creating Comments in Python Code

You’d probably think commenting code is a straightforward task.

Let’s take a look at a simple Python application that will print out simulated weather conditions. The code looks like this:

What does it all mean?

If you’ve been following my Python series, you know that I tend to break it all up into sections and explain what’s happening with each. Essentially, that’s what commenting is all about.

Let me show you how it works. We’ll start with the first section of the above code (after import random, because we know what that does), which is:


This section of code creates a function that defines options for two variables: weather_conditions and temperatures. We could add a single command above the function like this:


But is that enough? In the above code, the weather_conditions variable is obvious, but what about the temperatures? Is it Celsius or Farenheit? It might behoove you to add a comment indicating which it is. This leads us to another trick.

All Python comments start with the # character, so when the interpreter sees that character, it ignores what follows on that line. Thanks to that feature, we could indicate our temps are in F like this:


Now, the first block of code looks like this:


At this point, you have a better understanding of what’s going on and that’s key to comments. What you’re doing is ensuring anyone who reads your code can understand what’s happening.

Let’s continue with this example.

Our next section looks like this:


First, what does this section do? Simply put, it randomizes certain variables (weather_conditions and temperature from the previous section and defines two new variables — humidity and wind_speed — that are also randomized.

We could simply add the following comment:


That’s all fine and good, but we still might want to clarify the humidity and wind_speed variables as percentage and mph (for clarity). That section would then look something like this:


We then create another function that first calls our first function to get weather data and then formats and prints a friendly weather forecast that includes:

  • Condition
  • Temperature
  • Humidity
  • Wind Speed

Our first comment might be something like this:


In this block of code, we don’t really have to get much more granular than that, because we already have a few definitions included (such as F, %, and mph).

Our last bit of code is this:


The first line in the above sample checks to see if the file is being run as the main program. If the condition is True, the second line is executed. So our comment might be:


Our entire code (with comments) now looks like this:

You now understand what each code block does because it’s been commented.

Consider Keeping Comments Outside the Function

One thing to keep in mind is that some programmers prefer to place their comments within a function like this:


I prefer to keep those types of comments outside the function because it makes them easier to read and understand. It’s fine to add inl

ne comments when necessary, but the key is to strike a good balance between not enough and too much. Don’t go overboard with your explanations, but don’t leave much to the imagination. You want simple, succinct comments that make it very clear what each section of code does.

# Keep your comments short and sweet but effective and they’ll serve you well. And one other
# thing to keep in mind is that if your comments take up more than one line they should look like
# this paragraph.

As an aside, if you were to run the above application, it would print out results like this:

=== Weather Forecast ===
Condition: Windy
Temperature: 20°F
Humidity: 54%
Wind Speed: 5 mph
========================

And there you have it.

Group Created with Sketch.
TNS owner Insight Partners is an investor in: Simply.
TNS DAILY NEWSLETTER Receive a free roundup of the most recent TNS articles in your inbox each day.