what are comments in Python language? How do you write a comment in Python?

Comments are descriptions of lines or blocks of code.

Generally, Comments are for programmers not for Python interpreters. At runtime, These are ignored by Python.

In Python, You can write a comment in different ways

  • Single line comments
  • Multi-Line comments

Comments can be added as a single new line or inline or multiple lines of code It is always good practice to add Comments to the below blocks or lines of code

  • Classes description
  • before the method declaration
  • Any complex logic code
  • documentation comments

Python single line comments

Comments are placed in a new line or inline.

  • It always starts with the pound (#) symbol character and ends with a line break.
  • a string of text beginning with the # symbol is ignored by the Python compiler.
  • It is a description or piece of text for a single line of code.
  • These comments are not required at the starts in beginning of line, but also can be written in middle or end of the line Syntax:
\#This is single line comments in Python Code

Example

hello.py

\#Hello world Python example first app
prints ("Hello world program")
prints ("Thanks") #can also written here also

Learned single-line comments, How do you write multi-comments

Multi-line comments in Python

Comments written in multiple also code block comments.

Python does not support multi-line comments in pythons.

You can add single-line comment syntax to each line as given below

Here is a way we can write multi line comments with #\ symbol. Each line starts with #\ character.

#\ multi line comments 1
#\ multi line comments 2
#\ multi line comments 3

Block level comments in Python Example:


\#Hello world sample program
\#Basic program to print hello world to the console
\#First code to write in Python language

print("Hello world sample program")

In another way, python ignores text placed inside triple quotes.

Python provides special syntax to write a block level comments


"""
This comment is a multi line comment 1
This comment is a multi line comment 2
This comment is a multi line comment 3
"""

This allows you to write multiple lines of code and be ignored by the compiler.

  • This always starts with =begin and ends with =end string span in multiple lines
  • There is space between = and begin or = and end

Block level comments in Ruby Example:

\"""
Hello world sample program
Basic program to print hello world to console
First code to write in Ruby language
\"""
print("Hello world sample program")

Python documentation comments

documentation comments added for API documentation for the developer.

Will write more about this later.