Beginner’s Guide to Python Block Comments (With Code Examples)

Travis Cuzick
Travis Cuzick
hero image

Writing Python code that works is just the first step. The real challenge is ensuring your code is easy to understand and maintain. Not just for yourself, but for anyone else who might need to work with it in the future.

This is where comments come in. Comments allow you to document your code, making it more accessible and easier to follow.

There are several 'types' of comment you can use in Python, each suited for different purposes. I’ve already covered docstrings and general best practices.

So now, let’s dive into block comments - an essential tool for adding clarity to your code, particularly when dealing with complex logic or larger projects.

In this guide, I’ll break down how block comments work, when to use them, and why they’re crucial for writing clean, maintainable Python code.

Not only that, but I'll also cover how they differ from what you've seen before, so let’s get started.

Sidenote: If you find any of this confusing, or simply want a deep dive into Python, check out Andrei's Python Bootcamp course taken by 200,000+ people. I personally think it's one of the best Python courses online (and not just because I'm also a ZTM instructor!).

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!

Block comments, inline comments, and docstrings: What's the difference and when should you use each?

In Python, code annotations come in three main forms:

Each type serves a specific purpose, and knowing when to use each will help make your code more readable and maintainable.

Block comments

Block comments are used to explain why certain decisions were made in your code.

They provide essential context for larger sections of code or workflows that might not be immediately clear from the code itself - which is incredibly helpful for other users or even yourself in the future.

code issues

As for appearance, block comments are typically placed above the code they describe and can span multiple lines, allowing you to thoroughly explain the rationale behind your approach.

For example

# This function calculates the area of a rectangle <<These are block comments
# by multiplying the length and width. It assumes both
# inputs are positive numbers.
def calculate_area(length, width):
	return length * width

In this example, the block comment clarifies the assumptions made about the inputs, and helps anyone reading the code understand not only what the function does, but also why it works the way it does.

This level of explanation becomes especially important when dealing with more complex logic or workflows and automation scripts.

Inline comments

Inline comments provide brief explanations for specific lines of code, and are placed at the end of the line. They are often used to give quick insights into what that particular line is doing.

For example

x = x + 1  # Increment the value of x by 1

Inline comments are best used when a line of code might be tricky or non-obvious at first glance.

However, while useful for clarifying individual lines, inline comments should be used sparingly. Overloading your code with too many inline comments can clutter the logic and make the code harder to read.

But when used thoughtfully, inline comments can provide clarity without disrupting the flow of your code. The key is balance - use them when necessary but rely on clean, self-explanatory code when possible.

Docstrings

I cover these in more detail in this guide, but docstrings are formal descriptions used to document what a function, class, or module does. Basically, they provide details about the purpose of the code, its parameters, return values, and behavior.

An added bonus is they can be extracted into external documentation by tools like Sphinx, making them invaluable in larger projects or shared libraries.

sphinx

As for appearance, they are written in triple quotes and placed at the start of a function or class, making them accessible for documentation tools and in-line help within IDEs.

For example

# This function calculates the factorial of a number using recursion.
# It keeps multiplying the number by the factorial of the previous number,
# stopping when it reaches 1.
def factorial(n):
	if n == 1:
    	return 1
	else:
    	return n * factorial(n - 1)

A common source of confusion is that both docstrings and block comments can span multiple lines, but they serve different purposes.

Tl;DR

  • Block comments explain the reasoning or logic behind the code, focusing on the why. They’re typically used to clarify the thought process, design decisions, or context that might not be obvious from the code itself
  • Docstrings provide formal documentation of what the code does. They describe inputs, outputs, and behavior and are essential for writing reusable code, especially in libraries or large projects where external documentation is required
  • Inline comments are short explanations for individual lines of code

With those differences sorted, let’s get into how to use block comments properly, and cover some common mistakes and best practices.

How to use Python block comments effectively

Implementing and adding block comments is insanely easy. All you need to do is add a # at the start of each line.

That being said, there are some nuances and tips I recommend you follow.

Always place block comments directly above the code they describe

Block comments should always go right above the code they’re explaining. This way, when someone (or you) is reading through the code, they can understand the purpose or logic behind it before diving into the details.

For example

# This function checks if the user is authorized by validating
# their session token to prevent unauthorized access.
def is_authorized(user):
	return user.has_valid_token()

People will expect to find them here also, so always practice writing clean code.

Always explain why the code exists

Your code already shows what it’s doing, so your comments should focus on why. Is there a reason you structured your automation this way? Are there edge cases being handled?

Block comments are your chance to clarify your design choices and make sure others understand your thinking.

For example

If you have retry logic built into an automation script, make sure to explain why it’s there.

# We check the user's session here to avoid making unnecessary
# API requests if the session has expired.
def fetch_data(user):
	if user.is_session_active():
    	return get_data(user)

This is especially valuable in automation, where workflows or decision logic might not be immediately obvious to someone else.

Keep comments concise, but informative

Although we want to explain ‘why’ our code is written in a particular way, block comments should still be short and to the point, giving just the right amount of information to make the code understandable.

Simply put, you want to provide enough context without overwhelming the reader.

For example

Automation scripts often deal with resource management or external API calls, so a quick comment explaining why you're making certain decisions can make the script much easier to follow.

# Only fetch the user's data if their session is active,
# to save resources and avoid unnecessary requests.
def get_user_info(user):
	if user.is_authenticated():
    	return fetch_user_data(user)

Notice how simple the comment is? It covers just what you need to know. In this case, the comments explain the key decisions that influence how the code behaves under certain conditions.

Always remember to update comments as your code changes

One of the most common mistakes that Python developers make is leaving old comments behind when the code changes. Always review and update the block comments to match. Outdated comments can be both misleading and confusing.

For example

Let’s say there's a situation where you originally wrote a function for validating user sessions and then repurposed it to generate user IDs. You would want to update your comments to reflect that change:

# This function used to validate sessions, but now generates
# a unique user identifier for new records.
def generate_user_id():
	return uuid.uuid4()

Notice how in this comment, we’ve also made a note of what used to happen at this point for further context? This keeps everything aligned and prevents confusion down the road.

Start using block comments in your own code today!

So as you can see, well-placed block comments not only help you explain your code’s intent but also make it easier for others to follow, especially as projects become more complex. They’re an essential tool for writing clean, professional code that’s easy to revisit and share.

Next time you’re working on a Python project, be sure to use block comments to keep your code organized and understandable - even if it’s just a personal project. It’s a good practice to get into, and such a simple step that both your future self and teammates will thank you for!

P.S.

Remember - If you want to go from complete beginner to being able to build any Python project or app your mind can think of, 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! (You'll be surprised just how many tasks you can start to automate, and how free time you can add to your week once you learn this).

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!

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

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

Learn how to write comments in Python to simplify your code, improve collaboration, and ensure easy debugging with this comprehensive beginner’s guide.