- Aliases
- and operator
- Booleans
- Classes
- Code blocks
- Comments
- Conditional statements
- Console
- Data structures
- datetime module
- Decorator
- Dictionaries
- Docstrings
- enum
- enumerate() function
- Equality operator
- Exception handling
- False
- File handling
- Floats
- For loops
- Formatted strings
- Functions
- Generator
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Integers
- Iterator
- Lambda function
- Less than operator
- Less than or equal to operator
- List append() method
- List comprehension
- List insert() method
- List pop() method
- List sort() method
- Lists
- Logging
- map() function
- Match statement
- Math module
- Modules
- Multiprocessing
- Multithreading
- None
- not operator
- OOP
- or operator
- Parameters
- print() function
- Random module
- range() function
- Recursion
- Regular expressions
- requests Library
- return statement
- round() function
- Sets
- SQLite
- String join() method
- String replace() method
- String split() method
- Strings
- time.sleep() function
- True
- try...except statement
- Tuples
- Variables
- While loops
- Zip function
PYTHON
Python Comment: Syntax, Usage, and Examples
In Python, comments are non-executable statements to annotate and explain the code to make it easier to understand. Comments get ignored by the Python interpreter.
How to Use Comments in Python
To add a comment, simply use the hash symbol (#
) along with your comment's text. The Python interpreter ignores any characters following the #
on the same line. For beginners, understanding comments is essential as they improve code readability.
# This is a single-line comment
print("Hello, world!") # This is a comment after code
Comments can also include inline comments, which appear after executable code on the same line, separated by at least one space.
# This is a single-line comment
print("Hello, world!") # This is an **inline comment**
When to Use Comments in Python
Comments are an important tool to keep Python programs maintainable. Especially in collaborative settings with multiple programmers or when you might need to update code after a long period, comments are essential.
Code Explanation
Comments can explain what the code does. Such explanations help other developers understand your code or reminds you if you revisit the code later.
# Calculate the square of a number
square = 5 ** 2
Code Documentation
In larger projects, comments often document the functionality of functions, classes, and modules in detail. For example, docstrings can document Python code by providing a detailed explanation of what a function or class does.
def add(a, b):
# Return the sum of two numbers
return a + b
Proper indentation ensures that comments are aligned with the code they explain, making it easier to follow.
Debugging
Temporarily commenting out parts of code is another common use of comments. During debugging, you can comment out code to isolate parts of a program.
# print("This line is commented out and won't execute")
print("This line runs and will print to console")
Examples of Using Comments in Python
Comments are a commonplace in any Python application. Here are some examples of comments you might run into:
TODOs and FIXMEs in Open Source Projects
Open-source projects (but also other software) might use comments to note enhancements, bugs, or improvements for the future.
# TODO: Optimize this loop for large datasets
for i in range(10000):
print(i)
Complex Algorithms
For a complex algorithm, comments might describe steps or logic, making the code easier to follow and maintain.
# Step 1: Initialize the sum variable
sum = 0
# Step 2: Loop through numbers 1 to 10
for num in range(1, 11):
# Step 3: Add number to sum
sum += num
# Step 4: Print the final sum
print("Sum is:", sum)
Legal or Licensing Comments
At the start of a script or file, comments often include copyright and licensing information.
# Copyright 2024 Mimo GmbH
Learn More About Comments in Python
Python Multiline Comment
Python lacks a specific multiline comment syntax like other programming languages. To create a multiline comment in Python, you can use multiple single-line comments or a triple-quoted string using '''
or """
.
"""
This is a multi-line comment
using a triple-quoted string.
"""
print("Hello, Python!")
Unless assigned to a variable, multi-line strings are ignored by the Python interpreter. While they can serve a similar purpose to comments, they are technically string literals, not comments.
Python Block Comment
Block comments in Python explain the code that follows them and are typically indented to the same level as the code.
def factorial(n):
"""
Calculate the factorial of a number
Argument:
n -- integer
Returns:
n! -- factorial of n
"""
if n == 0:
return 1
else:
return n * factorial(n-1)
Correct indentation is crucial to make block comments visually aligned with the code, helping readers navigate the script efficiently.
Identifiers and Comments
When writing comments, it's important to ensure that the identifier (e.g., variable name, function name) being discussed is clear and well-defined. This helps readers understand the purpose of the identifier in the code.
# The variable `total_sum` calculates the total of all values in the list
total_sum = sum([10, 20, 30])
How to Comment Out Multiple Lines in Python
In Python, commenting out multiple lines of code at once is a common need. Common scenarios are during debugging or when you want to disable certain parts of your code temporarily.
Most Python IDEs and editors support commenting out selected blocks of code with a keyboard shortcut. For example, in Visual Studio Code, you can select multiple lines and use CTRL + /
(Windows) or CMD + /
(macOS) to toggle comments on and off.
# This is the first line commented out
# This is the second line commented out
# print("These lines are not executed")
If your IDE has no shortcut for commenting out code, you can also use a triple-quoted string ('''
or """
). Such multi line comments are useful when the number of lines is too large for single-line comments to be practical.
"""
print("This line is commented out.")
print("This line is also commented out.")
This block will not affect the runtime unless syntax errors are present inside.
"""
Arrays and Comments
When working with arrays in Python, comments can clarify how the array is being manipulated. For instance, in NumPy or lists, comments can explain transformations applied to the array elements.
# Multiply each element in the array by 2
array = [1, 2, 3]
array = [x * 2 for x in array]
print(array) # Outputs: [2, 4, 6]
Python Docstrings
In Python 3, using docstrings for documenting Python code is highly encouraged. Docstrings serve as string literals directly associated with the objects they document. They also ensure that documentation is available at runtime via the help()
function. Unlike comments, docstrings are associated with code elements like functions or classes and are written using triple quotes.
def greet():
"""This is a docstring. It describes what the function does."""
return "Hello, World!"
By following these guidelines and understanding how comments and docstrings enhance readability and documentation, programmers can make their Python code more accessible and easier to maintain.
End of the Line Comments
Comments written at the end-of-the-line of a code statement can offer quick insights without requiring additional lines.
x = 42 # This is the answer to the ultimate question of life
Best Practices for Commenting
Good comments explain "why" the code does something rather than "how" it does it. Effective comments are concise and relevant, aiding understanding without overwhelming the reader. Over-commenting can clutter the code and reduce readability, so it's important to find a balance.
# BAD: Increment i by 1
i += 1
# GOOD: Handle edge case where i needs manual increment
i += 1
Check out our Python tutorial to deepen your understanding of comments and other Python essentials.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.