How to Write Python Comments

How to Write Python Comments

Comments can be used to explain Python code.

Comments can be used to make the code more readable.

Comments can be used to prevent execution when testing code.

Creating a Comment:

Comments starts with a #, and Python will ignore them:

#This is a comment
print("Hello, World!")        

Comments can be placed at the end of a line, and Python will ignore the rest of the line:

print("Hello, World!") #This is a comment.        

A comment does not have to be text that explains the code, it can also be used to prevent Python from executing code:

#print("Hello, World!")
print("Cheers, Mate!")        

Multiline Comments:

Python does not really have a syntax for multiline comments.

To add a multiline comment you could insert a # for each line:

#This is a comment
#written in
#more than just one line
print("Hello, World!")        

Or, not quite as intended, you can use a multiline string.

Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it:

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")        

As long as the string is not assigned to a variable, Python will read the code, but then ignore it, and you have made a multiline comment.


Learn to Cpde
LEARN TO CODE

Ilyas Qasim

W3Schools.com


To view or add a comment, sign in

More articles by Ilyas Qasim

  • Python Basics Data Types Every Developer Should Know!

    Built-in Data Types: In programming, data type is an important concept. Variables can store data of different types…

  • Python Global Variables Declaration and Usage ❗

    Variables that are created outside of a function (as in all of the examples in the previous article are known as global…

  • Python Output Variables!

    The Python print() function is often used to output variables. In the print() function, you output multiple variables…

  • Python Basics Assigning Multiple Values to Variables Made Simple ❗

    Python Variables - Assign Multiple Values: Many Values to Multiple Variables. Python allows you to assign values to…

  • Python Variable Names

    A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for…

  • Python Variables!

    Variables are containers for storing data values. Creating Variables: Python has no command for declaring a variable.

  • Python Syntax!

    Execute Python Syntax: As we learned in the previous page, Python syntax can be executed by writing directly in the…

  • Python Getting Started

    How to Install Python Many PCs and Macs will have python already installed. To check if you have python installed on a…

  • What is Python?

    Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.

  • MY FIVERR GIG:

    https://www.fiverr.

Others also viewed

Explore topics