MS in Computer Science: Machine Learning and Artificial Intelligence
Woolf University
Popular
MS in Computer Science: Cloud Computing with AI System Design
Vishlesan I-Hub, IIT Patna
Professional Fellowship in Data Science and Agentic AI Engineering
Vishlesan I-Hub, IIT Patna
Professional Fellowship in Software Engineering with AI and DevOps
IBM & Microsoft
Advanced Certification in Data Analytics & Gen AI Engineering
IBM & Microsoft
Advanced Certification in Web Development & Gen AI Engineering
Your Success, Our Mission!
3000+ Careers Transformed – Be Next!
Your Success, Our Mission!
3000+ Careers Transformed.
Course Outline
Literals in Python - What are Python Literals?
Variables in Python (Python Variables)
Indentation in Python (With Examples)
Comments in Python (With Types and Examples)
Operators in Python
Modulus in Python
Comments in Python (With Types and Examples)
Last Updated: 9th December, 2024
Comments are notes added to the code to explain what the code is doing. They are not executed by the program but are used to help other programmers understand the code. In this tutorial, we will learn about comments in detail.✍️💻
What are Comments?
Comments are a critical aspect of coding that can help to explain what your code does and why you wrote it a certain way. They are also essential for collaborating with other developers and maintaining and updating code over time. Let's see how comments can be critical in a company setting. Envision that you simply work for a budgetary administrations company creating a modern calculation for exchanging stocks. The calculation is complex and includes a parcel of distinctive calculations and decision-making forms. As we begin writing, we can explain our code to other group individuals, but what in case somebody inquires me about the same thing one month afterward? Can I clarify the code? I would have trouble following what each portion of the code was doing. Without comments, it would be troublesome for other engineers on your group to get it how the calculation works and how to alter it on the off chance that is vital."Comments are a awesome way to keep track of what you've done or to clarify why you've taken certain steps. They can be inconceivably valuable for investigating purposes as well.”
Why are They Used?
Comments are added to the code for several reasons, including:
Providing information to other programmers: Comments can help programmers who may be reading or modifying the code understand the purpose of the code, how it works, and any potential issues that may arise.
Documenting the code: Comments can be used to document the code to make it easier to maintain and update in the future. This is especially important when working on large projects or multiple programmers are working on the same codebase.
Debugging the code: Comments can help debug the code by allowing the programmer to isolate and troubleshoot specific parts of the code.
In Python, comments are signified by a '#' image. When the '#' image is put at the starting of a line, everything after it is considered a comment. Comments can also be utilized to disable code that you simply do not need to run briefly. This may be valuable when testing a program and seeing what happens when certain parts of the code are expelled. She begun including comments to her code. At first, it was a moderate process, as she was still getting utilized the idea of including comments to the code. However, after a few time, she found the rhythm and started to include increasingly comments.
# Python program to find the factorial of a number provided by the user.(comment)
# change the value for a different result(comment)
num = 7
# To take input from the user (comment)
#num = int(input("Enter a number: ")) (comment)(You can uncomment this part and try to run in IDE)
factorial = 1
# check if the number is negative, positive, or zero (comment)
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Types of Comments in Python
There are two types of comments in Python:
1. Single Line Comment in Python
Single line comments in Python add a short description or 💬 note about a single line of code. They start with a '#' symbol and continue until the end of the line.
# This is a single-line comment
# This is another single-line comment
2. Multi Line Comment In Python
Multiline comments in Python add longer descriptions or notes about multiple lines of code. They start and end with three single quotes ("''') or three double quotes (""").
''' This is a multi-line comment.
It can span multiple lines. '''
Multi-line comments are also used as docstrings, a special type used to document the purpose and usage of functions, modules, and classes. Docstrings can be accessed using the help( ) function in Python. For example:
def my_function():
""" This is a docstring for my_function.
It explains what the function does
and how to use it. """ # function code here
It's worth noting that although multi-line comments can be used as docstrings, they are not required to be in a specific format or style. Several conventions for writing docstrings in Python, such as the Google and NumPy styles, provide guidelines for writing clear and helpful documentation.
Best Practices for Different Contexts
1. Inline Comments
Purpose: Use inline comments to explain specific lines of code that might not be immediately clear.
Best Practice:
Keep inline comments brief and place them on the same line as the code they describe.
Purpose: Use block comments to provide detailed explanations for a section of code.
Best Practice:
Use them to describe the logic, purpose, or assumptions behind a code block.
Start each line of a block comment with a # symbol for consistency.
Example:
# Check if the input is a prime number.
# Iterate through numbers from 2 to the square root of the input.
# If any number divides the input without a remainder, it's not a prime.
def is_prime(num):
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
3. Function-Level Comments
Purpose: Provide a high-level overview of what a function does.
Best Practice:
Use docstrings to describe the purpose, input parameters, return values, and any exceptions the function might raise.
Follow a standard style (e.g., Google, NumPy) for clarity and consistency.
Example:
def factorial(n):
"""Calculates the factorial of a given number.
Args:
n (int): A non-negative integer.
Returns:
int: The factorial of the number n.
Raises:
ValueError: If n is negative.
"""
if n < 0:
raise ValueError("Negative numbers are not allowed.")
return 1 if n == 0 else n * factorial(n - 1)
4. Class-Level Comments
Purpose: Document the overall purpose and functionality of a class.
Best Practice:
Use docstrings at the start of the class definition to describe the class's role and its attributes/methods.
Example:
class BankAccount:
"""Represents a bank account.
Attributes:
account_number (str): The unique identifier for the account.
balance (float): The current account balance.
"""
def __init__(self, account_number, balance=0.0):
self.account_number = account_number
self.balance = balance
5. Comments for Complex Logic
Purpose: Break down and explain complex algorithms, mathematical calculations, or unusual techniques.
Best Practice:
Use comments to clarify why the code is written a certain way rather than just what it does.
Example:
# Use dynamic programming to calculate the nth Fibonacci number.
# Store intermediate results in a dictionary to avoid redundant calculations.
def fibonacci(n, memo={}):
if n in memo:
return memo[n]
if n <= 1:
return n
memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo)
return memo[n]
6. Temporary Comments
Purpose: Disable specific parts of the code temporarily during debugging or testing.
Best Practice:
Clearly indicate the purpose of the temporary comment to avoid leaving it in production code accidentally.
Example:
# Temporary change: Skipping database connection for local testing
# db.connect()
7. Configuration and Environment Comments
Purpose: Document configuration variables, constants, or environment-specific settings.
Best Practice:
Provide context about why specific values are chosen or their intended use.
Example:
# API endpoint for production environment
API_URL = "https://api.example.com/v1"
8. Versioning and Change Logs
Purpose: Keep track of changes, especially in collaborative projects.
Best Practice:
Use comments to document changes with a date and a brief description.
Example:
# Updated on 2024-12-01: Fixed the logic for negative inputs.
9. Avoiding Unnecessary Comments
Purpose: Avoid comments that are redundant or state the obvious.
Best Practice:
Let the code speak for itself when variable names and function names are descriptive enough.
Bad Example:
x = 10 # Assign 10 to x
Good Example:
max_retries = 10 # Maximum number of retries allowed for API requests
How to Write Better Python Comments
Writing good comments is an essential skill for any programmer. Here are some tips for writing better comments in Python:
Be concise and clear: Comments should be brief and to the point. They should explain what the code does, not how it does it. Use simple and clear language that is easy to understand.
Use comments sparingly: Comments should be used only when necessary. Avoid adding comments that repeat what the code already says or comments that are not relevant to the code.
Keep comments up to date: If the code changes, update the comments accordingly. Outdated comments can be more harmful than no comments at all.
Use descriptive variable and function names: Using descriptive names for variables and functions can make the code easier to read and reduce the need for comments.
Use docstrings for functions, modules, and classes: Docstrings are a special type of comment that provide documentation for functions, modules, and classes. Use them to explain the purpose, usage, and arguments of the function and any side effects or exceptions it may raise.
Use comments for complex or unusual code: If the code is complex or uses unusual techniques, comments can help explain its logic.
Avoid unnecessary comments: Avoid adding comments unrelated to the code or comments that are too personal or informal.
Follow a style guide: A style guide can ensure that your comments are consistent and easy to read. The Python community has several style guides, such as PEP 8 and Google Python Style Guide.
Importance of Using Comments in Python
Why is it essential to add comments to your code:
Understanding the code: Comments can help you and other programmers to understand the code and its purpose. They provide additional context and help to explain how the code works.
Maintaining the code: Comments can help you to keep the code by making it easier to modify and update. When you return to the code later, comments can help you remember what you were trying to do and why.
Collaboration: Comments can help you and your colleagues to collaborate on the code. By adding comments, you can explain your thought process and help others to understand your code.
Debugging: Comments can help you to debug the code by providing hints and explanations about what each part of the code is doing. This can help you to find and fix bugs more quickly.
Learning: Comments can help you to learn from your code and other people's code. You can learn new programming techniques and best practices by reading and writing comments.
Conclusion
In summary, comments are an essential part of programming in Python, as they help to make code more readable and understandable 🔎📝📝. They can also be used to temporarily disable code and provide notes to yourself about what specific parts of the code are doing:thinking:💭.
Key Takeaways
This lesson provides a detailed explanation of comments in Python, including their purpose, types, and best practices for writing them.
The importance of using comments is also discussed, such as helping with understanding, maintenance, collaboration, debugging, and learning from code.
The lesson includes an explanation and examples of single-line and multi-line comments and docstrings.
Quiz
What are comments in Python?
A type of variable in Python
A way to write code in Python
A way to add explanatory text or notes within the code that do not affect the program's execution
A way to execute a program in Python
Answer: c) A way to add explanatory text or notes within the code that do not affect the program's execution
Why are comments used in Python?
To add complexity to the code
To make the code harder to read
To explain the purpose of the code, how it works, and any potential issues that may arise
To make the code run faster
Answer: c) To explain the purpose of the code, how it works, and any potential issues that may arise
How are single-line comments denoted in Python?
With three single quotes (''')
With three double quotes (""")
With a '#' symbol at the beginning of the line
With a '*' symbol at the beginning of the line
Answer: c) With a '#' symbol at the beginning of the line
What is the purpose of docstrings in Python?
To disable code temporarily
To add descriptive names for variables and functions
To provide documentation for functions, modules, and classes
To explain complex or unusual code
Answer: c) To provide documentation for functions, modules, and classes
Which of the following is a tip for writing better comments in Python?
Make comments as long and detailed as possible
Use comments for every line of code
Use simple and clear language that is easy to understand
Use comments for personal thoughts and feelings
Answer: c) Use simple and clear language that is easy to understand
Module 2: Basics of Python ProgrammingLesson 4: Comments in Python (With Types and Examples)
Module 2: Basics of Python ProgrammingLesson 4: Comments in Python (With Types and Examples)