How to Use Comments in Python 3?

Photo of author

By admin

It happens with every programmer, be it an expert or a novice, that you need to go back to the code you wrote and make changes in it. When you are writing a small code, for example, adding two numbers, the program is a child’s play. You can do it with the snap of a finger. But what about a complex program on which your entire team is working day and night? What if you need to go over the entire code? It looks like nothing but a mess.

Many people have worked on the code and you can’t understand why the programmer wrote it. In such a situation, comments come to your aid. These are small explanations that tell everyone why a code is written in a particular way, and what does it signify. Making comments while writing the code or immediately after writing the program can be very helpful as what you wrote is still fresh in your mind.

Python is a programming language that has gained popularity among programmers and many programs have been written using it. It is a language that is simple and thus programmers use it on a large scale, thus, the question always arises as to how to use comments in Python 3.

In this blog, we will discuss various kinds of comments that you can use in Python 3. So hop on.

Why Writing Comments in Python 3 is Important?

Before asking how to write comments in Python 3, you must understand its importance. The benefits of writing comments in Python 3 are:

  1. Better Understandability: If a beginner looks at your code, he/she must be able to understand it. If they are going to work alongside you or take your work further, they must know what is going on in code. Explanatory comments provide better understandability even to those who are not experts in programming.
  2. To Make Quicker Change: If you look at your written program after a while, it will take too much of your time only to read and understand it. With proper comments, you can understand your program, make quicker changes, and save a lot of time.
  3. It is a Good Habit: If there is a concept called good coding habit, writing comments fall under that criteria. When you keep writing comments as you use the code, it proves to be very helpful in the long run.

How to Use Comments in Python 3?

Comments in Python 3 are not of a single type that works for every situation. People may confuse using comments in Python 3 with adding comments in a shared document. But these are different. Every comment has a purpose, and there is a proper way of writing it, which you will learn here.

1. Syntax of a Comment

First of all, you must know the syntax of a comment, i.e. the format in which a comment is written. It always starts with a hash, followed by a whitespace character. So, a simple comment is written as:

# Hello!

You don’t execute a comment. It is not part of a program. You can take it as a backend thing that is meant for human use and not for computers to read it and execute it. A comment is not deployed when a program is written.

So, in a simple program, it will look like this:

# Print “Hey, Buddy!” to console

print (“Hey, Buddy!”)

In an iterating loop, e.g. a loop, the comment will look like:

water.py

# Define water variable as strings

water = [‘sparkling’, ‘Chilled’, ‘Tap’, ‘Normal’]

# for loop that iterates over water list and prints

each string item

for water in waters

print (water)

Remember, a comment is indented in the same way as the code for which it is written. To understand the indentation, you can go over the again function in this Calculator Program.

# Define again() function to check with user if they want to use the program again

def again():

# Take input from user

calc_again = input(”’

Do you want to use the program again?

Please choose between Y/N for Yes and No.

”’)

# If user types Y, use the program again

if calc_again == ‘Y’:

calculate()

# If user types N, Exit the program after saying goodbye to user

elif calc_again == ‘N’:

print(‘See you later.’)

# If user types another key, run the function again

else:

again()

You must understand the essentials and importance of a comment to maintain its worth. It is not just the creator of the program, who uses the comment, but others as well. If you don’t use it in alignment with the code, there is no point in writing it as it will only cause more confusion. The comment is supposed to be simple and not an explanatory one describing what and how of the code but an answer to a simple ‘why’.

2. Block Comments

These comments are used when the code is not a regular one but a complicated one that needs a good comment. The indentation and syntax rules are the same for block comments as well.

As they are long comments, you need to write each line starting with a hash mark. In case of more than one paragraph, separate it by a line.

You can go over this example of a block comment explaining the main () function.

# The main function will parse arguments via the parser variable. The

# use will define the arguments. This will forward the word arguments and

# the filename user wants to use, and in case of wrong argument

# it will pop up the text file.

def main():

parser = argparse.ArgumentParser()

parser.add_argument(

“word”,

help=”look for this word in the file.”

)

parser.add_argument(

“filename”,

help=”the path to the text file to be searched through”

)

When you are writing complex code, block comments can be very useful but that doesn’t allow you to stuff the code with comments. Leave room for other programmers to understand it. Write only what is necessary.

3. Inline Comments

When your comment is written in the same line as the concerned code, it is called an inline comment. It also follows the syntax and looks like this:

[code] # Inline comment for the code

When you are writing a lengthy program and a complex one on top of that, in such a case, you need inline comments to explain the difficult or tricky parts. If you think this line of code is important and you will need to go over it in the future, or if you want to highlight it for your team, this comment will come in handy.

For example, if you have written a program that does not contain anything about a complex number but a line of code returns a complex number, you can highlight it by an inline comment for your team members.

x = 5.8+ 4j # Create a complex number

You can insert it as an explanation or additional information as to why you did that.

x = 8 # Initialize x with an arbitrary number

Use the inline comments after carefully thinking.

4. Commenting Out Code

When you write or debug a program, you can check it a thousand times. You can try certain permutations and combinations to find out which line of code is causing the problem. You can’t simply delete a line of code to execute the program. You can comment it out i.e. exclude a line of code while testing the program.

You can use comments to resolve this. The comments can help you decide between loops as well as a while loop and for a loop.

Here’s an example to understand it:

import random

number = random.randint(1, 20)

# user’s_guess_number = 0

for i in range(6):

# while user’s_guess_number < 6:

print(‘Guess a number between 1 and 20:’)

guess = input()

guess = int(guess)

# user’s_guess_number = user’s_guess_number + 1

if guess < number:

print(‘You guessed a lower number’)

if guess > number:

print(‘You guessed a higher number’)

if guess == number:

break

if guess == number:

print(‘You have guessed the correct number!’)

else:

print(‘You did not guess the correct number. It is ‘ + str(number))

It is a simple way of finding out the problem section in your program.

Conclusion

Coding is fun. Writing programs is amazing. Being a programmer, you invest hours in writing every single function, action, and instruction of a program. Any problem in any part of the program cannot be tolerated. Thus, it is essential to check every line carefully as a problem can lie anywhere.

As you work in a team, your fellow members, even you should understand the reason behind writing a particular line or program. Comments are a way to help it. You can add an answer to “why” in a single line, you can add a block comment for a complex one, an inline comment to describe a tricky line or you can take help of a comment out code as you are testing or debugging.

This guide covers every kind of comment you can use in Python 3. Hopefully, it has answered your question about how to use comments in Python 3.

Leave a Comment