🎁 Give the #1 gift request of 2024... a ZTM membership gift card! 🎁

Beginner's Guide to Using Comments in Python (With Code Examples)

Travis Cuzick
Travis Cuzick
hero image

Have you ever opened an old Python file and wondered, "What was I even thinking here?"...

Well, don’t worry because we’ve all been there. It’s easy to lose track of your thought process after some time away from your code, and that’s where comments can save the day. Think of them as sticky notes you leave for your future self, explaining the reasoning behind your code.

They are much more than just reminders though.

No joke but one of the major factors to moving into a senior role is clean code, documentation, and comment management. It's one of the major habits that people look for, so don't skip this!

In this guide, I’ll dive into how to use comments in Python effectively. You’ll learn not only about the different types of comments — single-line, multi-line, and inline — but also how comments can help you write more maintainable and professional code.

Let’s get started by looking at the multiple ways comments can benefit your coding workflow.

Sidenote: If you find any of this confusing, or simply want a deep dive into Python, check out Andrei's Python Coding course taken by 200,000+ people:

learn python

It’ll take you from an absolute beginner and teach you everything you need to be hired ASAP.

Alternatively, if you're already pretty good at Python and want to build some interesting and useful projects, why not check out my course on Python Automation:

learn python automation

It'll show you how to automate all of the boring or repetitive tasks in you life - and makes for some pretty stand out portfolio projects!

With that out of the way, let's get into this 5-minute tutorial!

What are comments in Python?

Imagine you’re assembling furniture with a set of instructions guiding you step-by-step. Comments in Python serve a similar purpose. They provide explanations or context, making even the trickiest parts of your code easier to understand.

For example

In Python, anything that follows a # symbol is a comment, meaning it's ignored by the interpreter.

# This line is a comment and will not be executed
print("Hello, world!")  # This prints a greeting to the console

So what’s happening here?

Well, in this code snippet:

  • The first line is a comment that provides context
  • While the second line contains code and an inline comment explaining what the code does. (Basically an explanation in this example)

When you run this program, it will output:

Hello, world!

But the comments won't affect the execution.

Why should you use comments in Python?

You might be wondering, "If comments don't change how my code runs, why should I bother using them?"

Simply put, comments are incredibly valuable, especially as your programs grow in size and complexity. They serve multiple purposes that can make your coding life much easier.

Heck, all of the benefits below pretty much fit in with any programming language that you choose to learn!

So let's get into them.

Benefit #1. They make your code more readable

When you or someone else reads your code later, comments help explain the logic and purpose behind it. That’s why it’s important to write comments that are clear and concise.

Avoid overly long explanations that could confuse the reader or distract from the code itself. A simple, well-placed comment can go a long way in helping others (and your future self) quickly grasp what your code does.

For example

# Calculate the area of a circle using the formula area = π * r^2
area = 3.14159 * radius ** 2

Here, the comment provides just enough context without overwhelming the reader, making it immediately clear what the formula does.

When you or someone else reads your code later, comments help explain the logic and purpose behind it. That’s why it’s important to write comments that are clear and concise.

A simple, well-placed comment can go a long way in helping others (and your future self) quickly grasp what your code does.

Benefit #2. Comments make it easier for maintenance and updates

Code evolves, and you’ll often revisit it to fix bugs, add features, or improve performance. Comments act as breadcrumbs, helping you retrace your thought process. As your code changes, though, so should your comments.

Outdated comments can lead to confusion, so it's essential to update them when necessary.

For example

If you originally wrote:

# Sends an email using SMTP
def notify_user(message):
	smtp.send_mail(message)

And later switched to using an API:

# Now uses an API instead of SMTP to send notifications
def notify_user(message):
	api.send_notification(message)

The updated comment reflects the changes in the code, preventing any misunderstanding down the line.

Benefit #3. Comments help when working with others

When collaborating with others, comments make your code more understandable, reducing the time it takes for someone else to figure out how things work.

This is especially helpful in larger teams or when sharing code with the open-source community. Comments are like silent teammates, guiding others through your thought process and intentions.

For example

# TODO: Optimize this loop to reduce execution time
for item in large_dataset:
	process(item)

This comment communicates to others (or your future self) that the loop is a potential performance bottleneck and might need improvement.

Benefit #4. Comments help with debugging and testing

When tracking down bugs, you often need to isolate parts of your code.

However, rather than deleting code to temporarily stop it from running, comments allow you to "comment out" sections instead. This keeps the code intact for future use, while making sure it doesn’t run during testing.

For example

# Temporarily disable the following line to test the function without logging
# log_event("Function started")

result = perform_calculation()

By commenting out log_event("Function started"), with the #, at the start of the line, you prevent it from running while keeping the code intact for later use. (You can then just delete the # to add it back in).

Benefit #5. Comments help to provide context and intent

Sometimes, the code alone doesn’t fully explain why a particular approach was taken, especially when dealing with complex business logic or algorithms.

Comments can help clarify the intent behind the code, making it easier to understand decisions that might not be immediately obvious.

For example

# Using the Fisher-Yates shuffle algorithm to randomize the list
def shuffle_list(items):
	# Implementation of the algorithm
	pass

This comment tells you that you’re not just shuffling a list, but that you’re specifically using the Fisher-Yates algorithm, which might have particular properties or implications.

Benefit #6. Comments help you learn to code!

This works in two different ways.

  • If you're new to programming, writing comments can also reinforce your understanding, explaining what each line does in your own words helps solidify concepts
  • Likewise, being able to read other peoples comments on their code helps you understand what is happening and grasp the content easier

Huzzah!

TL;DR: Comments are incredibly helpful

At its core, programming is about communication—between you and the computer, but also between you and other developers, including your future self.

Comments bridge the gap between code and human understanding. They make your code more approachable, maintainable, and collaborative.

Remember, code is read more often than it's written. A little effort in writing clear comments can save you a lot of time and headaches down the road.

The different types of comments in Python

Now that you know why comments are essential for making your code clear and maintainable, let's explore the different types of comments you can use in Python.

Whether you’re working on a small script or managing a complex automation project, knowing how to use comments effectively will simplify both your life and the lives of others reading your code.

There are three primary types of comments in Python:

  1. Single-line
  2. Multi-line
  3. Inline comments

Each serves a specific purpose, and mastering when and how to use them can make your code more readable, collaborative, and easier to debug.

Single-line comments: Your go-to option for quick notes

The most common type of comment you'll use is the single-line comment. Just start a line with the # symbol, and anything you write after that is ignored by Python when your script runs. This lets you leave notes or explanations without affecting how your program operates.

For example

Imagine you're writing a Python script to automate the backup of important files.

Well, here's how you might use single-line comments to give some clarity around the code:

# Import necessary modules for file manipulation
import os
import shutil

# Define the source and destination directories for backup
source_dir = '/path/to/source'  # Replace with your source directory
destination_dir = '/path/to/destination'  # Replace with your destination directory

In this snippet, the comments help you (and anyone else reading your code) understand what's happening. You're making it clear that you're importing modules needed for file operations and setting up directories for the backup process.

Also, the inline comments next to the variable assignments provide immediate context, showing where you need to specify your actual directories.

Multi-line comments: The best option for when one line isn't enough

Sometimes, a single line just doesn't cut it, and that's when multi-line comments come into play. You can create them by either stacking single-line comments or by using triple-quoted strings.

The main difference between these is how you format them inside your code.

How to use multiple single-line comments

Let's say you want to explain the overall purpose of your automation script:

# This script automates the backup process for critical files.
# It checks for files modified in the last 24 hours and copies them
# to a designated backup directory. This ensures that recent changes
# are always backed up without duplicating older files.

By stacking single-line comments, you're providing a detailed explanation that's easy to read. This is incredibly helpful when you or someone else revisits the code later.

How to use triple-quoted strings

Alternatively, if you're documenting a longer block of code or want a cleaner way to comment, you can use triple-quoted strings... (''' or """) to create multi-line comments.

While these are technically multi-line strings that aren't assigned to any variable, Python ignores them when they're not used, effectively treating them like comments.

them when they're not used, effectively treating them like comments.

"""
This section of the script handles the backup process.
It iterates through the source directory, identifies files
that have been modified in the last 24 hours, and copies them
to the destination directory.
"""

This method is especially useful if you want to temporarily disable a block of code during debugging or provide a detailed explanation without prefixing each line with a #.

Inline Comments: Use this option when you need to explain the tricky parts

Inline comments are placed on the same line as your code, or after it, and they're perfect for clarifying specific lines that might be complex or not immediately obvious.

For example

Here you can see an automation script that processes log files:=

for log_file in os.listdir(source_dir):
	full_path = os.path.join(source_dir, log_file)
	if os.path.isfile(full_path):
    	# Check if the file size is greater than 1MB
    	if os.path.getsize(full_path) > 1_000_000:
        	process_large_file(full_path)  # Handle large files differently

So what’s happening?

Well, the inline comment # Check if the file size is greater than 1MB explains why you're checking the file size in the if statement. While another inline comment after the function call clarifies that process_large_file is used for handling large files differently.

These comments give you immediate insights without interrupting the flow of your code, and also help you understand what part of the code is being referred to in the comment.

Bringing it all together: A real-world example

Now obviously you would probably be using each different version when commenting on a project, so let's see how these types of comments can work together in a real-world scenario.

Suppose you're using Python to automate the process of sending out email reminders for overdue tasks.

import smtplib
from email.mime.text import MIMEText

# Function to send an email reminder
def send_email_reminder(recipient_email, subject, body):
	"""
	Sends an email to the specified recipient with the given subject and body.
	"""
	# Set up the SMTP server connection
	smtp_server = 'smtp.example.com'
	smtp_port = 587
	sender_email = 'noreply@example.com'
	sender_password = 'yourpassword'  # Replace with your actual password

	# Create the email message
	message = MIMEText(body)
	message['From'] = sender_email
	message['To'] = recipient_email
	message['Subject'] = subject

	try:
    	# Establish a secure session with the server
    	server = smtplib.SMTP(smtp_server, smtp_port)
    	server.starttls()  # Start TLS encryption
    	server.login(sender_email, sender_password)
    	server.sendmail(sender_email, recipient_email, message.as_string())
    	server.quit()
    	print(f'Email sent to {recipient_email}')
	except Exception as e:
    	print(f'Failed to send email to {recipient_email}: {e}')

# Main script to find overdue tasks and send reminders
# This part of the code interfaces with your task management system
overdue_tasks = get_overdue_tasks()  # Assume this function retrieves a list of overdue tasks

for task in overdue_tasks:
	# Prepare the email content
	recipient = task.assigned_to_email
	subject = f'Overdue Task Reminder: {task.title}'
	body = f"""Hello,

This is a reminder that the following task is overdue:

{task.description}

Please take the necessary actions.

Best regards,
Your Automation Script"""

	# Send the email reminder
	send_email_reminder(recipient, subject, body)

What’s happening here?

Well, a fair few things:

  • Single-Line Comments explain the purpose of code blocks, like setting up the SMTP server connection or iterating through overdue tasks
  • Triple-Quoted Strings serve as a docstring for the send_email_reminder function, providing a clear description of what the function does
  • Inline Comments clarify specific lines, such as starting TLS encryption with server.starttls()

By using comments effectively, you're making your code more understandable and maintainable. This is especially important in automation scripts, where you might interact with external systems or perform complex operations that aren't immediately obvious.

Sidenote: Automation scripts often run unattended and may not be revisited frequently, so when issues arise, clear comments can save you significant time troubleshooting - even if you wrote the code yourself. It’s always hard to remember what you were thinking months later!

This is why it’s so vital to pick up the habit of adding comments to your code.

What’s next?

Comments might seem like small additions, but they have a big impact on how you and others interact with your code.

By explaining the "why" behind your code - especially in automations - you can transform your code from a set of instructions into a readable, maintainable, and collaborative masterpiece. (Or simply be a great reminder for how to fix what’s broken when you come back later).

The next step is just to start putting it into practice. It’s better to build the habit of doing this now vs trying to add it in once you’ve been coding for a while. Trust me on this - you’ll thank me later!

So the next time you're writing Python code, challenge yourself to add a few well-placed comments that explain not just the "what" but the "why" behind your choices.

Start simple, and over time, it’ll become second nature.

P.S.

Remember - If you want to dive deep into Python then be sure to check out Andrei's Complete Python Developer course:

learn python

It’ll take you from an absolute beginner and teach you everything you need to get hired ASAP and ace the tech interview.

This is the only Python course you need if you want to go from complete Python beginner to getting hired as a Python Developer this year!

Alternatively, if you're already pretty good at Python and want to build some interesting and useful projects, why not check out my course on Python Automation:

learn python automation

It'll show you how to automate all of the boring or repetitive tasks in you life - and makes for some pretty stand out portfolio projects!

Plus, as part of your membership, you'll get access to both of these courses and others, and be able to join me and 1,000s of other people (some who are alumni mentors and others who are taking the same courses that you will be) in the ZTM Discord.


Ask questions, help others, or just network with other Python Developers, students, and tech professionals.

More from Zero To Mastery

Beginner’s Guide To Python Automation Scripts (With Code Examples) preview
Beginner’s Guide To Python Automation Scripts (With Code Examples)

Use Python automation scripts to save time, reduce errors, and boost productivity. Perfect for all skill levels. Work smarter, not harder!

Potential Python Interview Questions preview
Potential Python Interview Questions

Are you taking a coding interview with Python? On rare occasions, you may be asked broad language questions before the technical interview: Here's 25 of them.

Beginner's Guide To The Python ‘Not Equal’ Operator (!=) preview
Beginner's Guide To The Python ‘Not Equal’ Operator (!=)

Master Python’s != operator with this beginner’s guide. Learn how it works, avoid common mistakes, and improve your coding with practical examples