Lesson 4: Python Comments


Introduction

Comments are an essential aspect of programming that allows developers to document their code, make it more readable, and provide explanations for various sections. In Python, comments are lines of text that the interpreter ignores during the execution of the program. This lesson will cover the purpose of comments, how to create them, and some best practices for using comments in Python code.

Why Use Comments?

  1. Explanation: Comments help in explaining the purpose and functionality of different parts of your code.
  2. Readability: Well-commented code is easier to read and understand, aiding both the original developer and others who may work on the code later.
  3. Testing and Debugging: Comments can be used to disable or comment out code temporarily, which is useful during testing and debugging.

Creating a Comment

In Python, comments start with the # symbol, and anything following the # on that line is considered a comment.

Example:

python

# This is a comment

print("Hello, World!")

Comments can also be placed at the end of a line, and Python will ignore the rest of the line.

Example:

print("Hello, World!")  # This is a comment

A comment does not have to be text that explains the code; it can also be used to prevent Python from executing code.

Example:

# print("Hello, World!")

print("Cheers, Mate!")

Multiline Comments

Python does not have a specific syntax for multiline comments, but there are two common approaches to achieve multiline comments.

1. Using Multiple Single-Line Comments

You can insert a # for each line of the comment.

Example:

# This is a comment

# written in

# more than just one line

print("Hello, World!")

2. Using Multiline Strings

Although not intended for comments, you can use multiline strings (triple quotes) to create a multiline comment. Python will ignore the string if not assigned to a variable.

Example:

"""

This is a comment

written in

more than just one line

"""

print("Hello, World!")

As long as the multiline string is not assigned to a variable, Python will read it but then ignore it, effectively treating it as a multiline comment.

Test Yourself With Exercises

Exercise:

Comments in Python are written with a special character, which one?

  • a) /
  • b) *
  • c) #
  • d) $

 

Post a Comment

0 Comments