W3Schools Learner's Blog

W3Schools Programming knowledge summary website

div

12/20/2021

Python Comments

 In Python (or any other programming language), comments are used to explain the source code. Comments describe the code, which helps in maintaining the application in the future.

Comments in python
# prints 4
print(2 + 2)
 
print(2 + 3)    # prints 5
 
"""
prints the sum of
two numbers which are 2 and 2
"""
print(2 + 2)

Types of comments in Python

Python supports writing simple single line comment as well as multi line comment as well.

Single line comment

A simple single line comment will start with a hash (#) character. Python runtime ignores any text written after the # character and treats as comment.

Simple comment
# This is a simple comment
print(2 + 2)
 
print(2 + 3)    # prints 5

Multi line comment

Python does not have anything special to write a multi-line comment. To write it, we can write multiple single-line comments.

I recommend this form of comment.

Multi-line comment
# This statement
# prints the sum of
# two numbers which are 2 and 2
print(2 + 2)

We can take advantage of a multi-line string literal (using triple quotes), which is not assigned to a variable. Python ignores string literals that are not assigned to any variable, and so it will not affect the program execution.

Un-assigned string literal
"""
This statement
prints the sum of
two numbers which are 2 and 2
"""
print(2 + 2)

Drop me your questions related to writing comments in python.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.