Python Comments

📝 Python Comments

Python Comments are non-executable statements used to explain code. They are ignored by the Python interpreter and do not affect program output.

Comments are helpful for:

✔ Explaining logic
✔ Documenting code
✔ Making code readable
✔ Debugging


✅ 1. Single-Line Comment

Single-line comments begin with the # symbol.

Example:

# This prints a message
print("Hello Python!")

✅ 2. Inline Comment

A comment written on the same line as code.

x = 10 # Assign value to x
print(x)

✅ 3. Multi-Line Comment

Python doesn’t have a specific multi-line comment syntax, but we use triple quotes " """ or ' '''' for documentation.

Example:

"""
This is a multi-line comment.
It explains the following code.
"""

print("Learning Python")

Another example:

'''
Multiple lines
used as comments
'''

print("Python is fun!")

🧩 Use Case: Documenting Functions (Docstrings)

Triple quotes are also used for docstrings — documentation for functions, classes, and modules.

Example:

def greet():
"""This function prints a greeting message."""
print("Hello!")
greet()

🎯 Python Comments Best Practices

✔ Write meaningful comments
✔ Don’t over-comment simple code
✔ Use comments to explain why, not just what

❌ Bad:

x = 10 # assigning 10 to x

✔ Good:

x = 10 # default starting value

▶ Example Program with Comments

# Define variables
name = "Vipul"
age = 25
# Display user information
print(f”My name is {name} and I am {age} years old.”)

Summary Table

Type Symbol Example
Single-line comment # # Comment here
Inline comment # x = 10 # Explanation
Multi-line comment ''' ''' or """ """ """This is multi-line comment"""
Docstring """ """ Function description

You may also like...