Comments in Python


TL ; DR

You add a single line comment in Python by typing # followed by any text:

# This is a comment!



Full lesson:

Comments are lines of code that Python will intentionally ignore (not execute). They don't do anything.

They're just used to create notes for yourself and others about what the code does.

There are two types of code comments in Python:


1. Single line comments:

We create single line comments by typing # and Python will ignore (not execute) any text between # and the end of the line.

Single line comments automatically end at the next line of code:

# Next line will greet the user:
print("Hello user!")

Output of this code:

Hello user!

We can also use single line comments at the end of a line to explain the code:

print("Hello user!") # This line greets the user
print("This is not a comment!")

Output of this code:

Hello user!
This is not a comment!

2. Multi-line comments

We can also comment multiple lines of code using multi-line comments.

We type ''' to begin the comment and type ''' to end the comment:

'''
This is a 
multi-line comment
print("This will not run")
Next line will greet the user:
'''

print("Hello user!")

Output of this code:

Hello user!

Assignment
Follow the Coding Tutorial and let's write some comments!


Hint
Look at the examples above if you get stuck.


Introduction

In this lesson, we will explore the concept of comments in Python. Comments are an essential part of writing clean, readable, and maintainable code. They help you and others understand the purpose and functionality of your code. Comments are particularly useful in scenarios where the code is complex or when you are collaborating with other developers.

Understanding the Basics

Comments in Python are lines of text that the interpreter ignores. They are used to explain the code and make it more understandable. There are two types of comments in Python: single-line comments and multi-line comments.

Single-line comments start with the # symbol, and everything after the # on that line is ignored by the interpreter. Multi-line comments are enclosed within triple quotes (''' or """), and everything between the triple quotes is ignored.

Main Concepts

Let's delve deeper into the key concepts of comments in Python:

Here is an example of a single-line comment:

# This is a single-line comment
print("Hello, World!")  # This prints a greeting message

And here is an example of a multi-line comment:

'''
This is a multi-line comment.
It can span multiple lines.
The code below prints a greeting message.
'''
print("Hello, World!")

Examples and Use Cases

Let's look at some examples to understand how comments can be used in different contexts:

Example 1: Explaining a function

def add(a, b):
    # This function adds two numbers and returns the result
    return a + b

result = add(5, 3)
print(result)  # Output: 8

Example 2: Disabling code

# The following line is disabled and will not run
# print("This line is commented out and will not execute")

print("This line will execute")

Common Pitfalls and Best Practices

Here are some common mistakes to avoid and best practices to follow when using comments:

Advanced Techniques

While comments are straightforward, there are some advanced techniques you can use to make your comments more effective:

Example of a docstring:

def multiply(a, b):
    '''
    This function multiplies two numbers and returns the result.
    
    Parameters:
    a (int): The first number.
    b (int): The second number.
    
    Returns:
    int: The result of multiplying a and b.
    '''
    return a * b

Code Implementation

Here are some well-commented code snippets demonstrating the correct use of comments:

# Function to calculate the factorial of a number
def factorial(n):
    '''
    Calculate the factorial of a number.
    
    Parameters:
    n (int): The number to calculate the factorial for.
    
    Returns:
    int: The factorial of the number.
    '''
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

# Calculate the factorial of 5
result = factorial(5)
print(result)  # Output: 120

Debugging and Testing

Comments can also be useful for debugging and testing your code. Here are some tips:

Example of a test case with comments:

def test_add():
    # Test case for the add function
    assert add(2, 3) == 5, "Test failed: 2 + 3 should be 5"
    assert add(-1, 1) == 0, "Test failed: -1 + 1 should be 0"
    print("All tests passed!")

# Run the test case
test_add()

Thinking and Problem-Solving Tips

When working with comments, consider the following strategies:

Conclusion

In this lesson, we covered the importance of comments in Python, the different types of comments, and best practices for using them. Comments are a powerful tool for writing clear and maintainable code. By mastering the use of comments, you can make your code more understandable and easier to work with.

Remember to practice writing comments and keep them up-to-date as your code evolves. Happy coding!

Additional Resources

For further reading and practice, check out the following resources: