Comments in Python

Learn how to comments and different types of comments with examples in Python programming language? By Bipin Kumar Last updated : December 17, 2023

Python Comments

Comments in Python are used to improve the readability of the code. It is useful information given by the programmer in source code for a better understanding of code and logic that they have used to solve the given problem to the reader. Comments are not executed during the compilation and also not show on the output.

Writing Python Comments

In Python, comments are done by using the hash (#) and delimiters ("" or ''') symbol with no whitespace between starting.

Types of Python Comments

There are two types of Python comments:

  1. Single line comment (#)
  2. Multi-line string as comment (''')

1. Python Single-Line Comments

In Python, single-line comments are used for comments one-line statements like explanations of different variables, functions, expressions, etc. To do single-line comments a hash (#) symbol is used with no whitespace when the comments go to the next line then must put one another hashtag(#) at the start of the next line.

Example to demonstrate Python single-line comments

Let's see an example and try to understand how we apply the single-line comments in the program.

# Single line comments example
# a program to print a given string and addition.

print("Welcome @ IncludeHelp")
a = 2
b = 5
print(a + b)

# addition of both numbers by using plus(+) sign.

The output of the above example is:

Welcome @ IncludeHelp
7

Explanation: In the above example, we placed single-line comments. Used print() method to print the statement, declared two variables, performed addition operation, and printed the result.

2. Python Multi-Line Comments

As we have seen in the above example that single-line comments, for multi-line we have to put a hash (#) symbol in each line. In Python, To overcome this problem multi-line string comments using delimiter (''') are provided. It is useful when does not fit in one line. For multiline string comments, we have to enclose the string with delimiter at both ends.

Note: A delimiter is a sequence of one or more characters.

Example to demonstrate Python multi-line comments

'''
Here we will check a given number n is even or odd 
with multi-line comments in Python.
'''
n = 6768

if n % 2 == 0:
    print("Even number.")
else:
    print("Odd number.")

The output of the above example is:

Even number.

Explanation: In the above example, we placed multi-line comments, took a number, and checked whether the number is EVEN or ODD using the conational statement, and printed the result using the print() method.

Python Tutorial

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.