← Back to Chapters

Python Comments

? Python Comments

⚡ Quick Overview

Comments are notes in your code meant for humans to read. Python ignores comments when executing code. They help explain what the code does and make programs easier to understand and maintain.

? Key Concepts

  • Comments are ignored by Python: They do not affect how the program runs.
  • Single-line comments: Start with the hash symbol #.
  • Multi-line comments: Often written using triple quotes """ or '''.
  • Purpose of comments: Explain complex code, improve readability, and help during testing.

? Syntax and Theory

Use the hash symbol # for single-line comments.

Use triple quotes """ or ''' for multi-line comments that can span multiple lines.

? Code Examples

? Single-line Comments
# This is a comment
print("Hello, Python!")  # This prints a message
? Multi-line Comments
"""
This is a multi-line comment
It can span multiple lines
"""
print("Python ignores this comment")

? Output and Explanation

? What happens when this runs?

In both examples, Python completely ignores the commented lines.

  • The single-line example prints: Hello, Python!
  • The multi-line example prints: Python ignores this comment

Comments are there only for humans. They help you remember why you wrote the code in a certain way and help others understand your logic.

? Tips and Best Practices

  • Keep comments short and meaningful.
  • Update comments when you modify the code.
  • Use comments to explain why something is done, not what — the code itself shows the “what”.

? Try It Yourself

  • Add single-line comments to explain each line in a small Python program.
  • Write a multi-line comment describing what a function does.
  • Try temporarily commenting out a line of code and observe the output.