In this tutorial, you will learn about Python comments.
What are Comments?
Comments are used to disable code, and the Interpreter does not execute commented code.
What is the use of Python Comments?
Python comments are used to add notes, explanations, or annotations within the code that the interpreter does not execute.
Python simply ignores all the text following a #.
Types of Comments in Python:
There are 2 types of Comments in Python.
1. Single-line Comments
Single-line comments start with the # symbol. Everything after the # on that line is considered a comment and is ignored by the Python interpreter.
Example:
# This is a single-line comment
x = 20 # This comment is after a statement
2. Multi-line Comments
Python doesn’t have an official multi-line comment syntax like some other programming languages. However, multi-line comments can be achieved using triple quotes (‘ ‘ ‘ or “””).
Example:
'''
This is a multi-line comment.
It spans multiple lines.
'''
print("Hello, World!")
Alternatively, multiple single-line comments can be used for multi-line comments:
# This is a comment
# that spans multiple lines
# using single-line comments.
When to Use Comments:
1. Explain Complex Logic: Use comments to clarify complicated or non-obvious parts of the code.
# Check if the user input is a positive integer
if number > 0:
print("Positive number")
2. Provide Metadata: Comments can be used at the top of a script to describe metadata like the author’s name, date of creation, and purpose of the program.
# Author: John Taylor
# Date: 2023-07-05
# Description: This script performs basic operations.
3. Disable Code: Temporarily comment out code for debugging or testing purposes.
# print("This line is commented out and won't run.")
print("This line will run.")
Python Comments – Questions and Answers
Q 1: What are comments in Python?
Ans: Comments are notes in code that explain logic and are ignored during execution.
Q 2: How do you write a single-line comment in Python?
Ans: Using the # symbol.
Q 3: Does Python support multi-line comments?
Ans: Python does not have official multi-line comments, but triple quotes are commonly used.
Q 4: Why are comments important?
Ans: Comments make code easier to understand and maintain.
Q 5: Are comments executed in Python?
Ans: No, comments are ignored by the Python interpreter.
Python Comments – Objective Questions (MCQs)
Q1. Which symbol is used to write a single-line comment in Python?
Q2. How do you write a multi-line comment in Python?
Q3. What happens when you put a # symbol before a line of code in Python?
Q4. Which of the following is a valid comment in Python?
Q5. What is the main purpose of comments in Python code?