Python

Comments in Python

Click for All Topics

Comments in Python

  • Comments are very useful elements in any programming language, including Python.
  • Comments are used to describe the logic of the code and make it more readable.
  • In Python, comments are those lines of code that are ignored by the interpreter during execution.
Best Practices for Using Comments
  1. Be clear and concise.
    • Write comments that are easy to understand, providing clarity in complex sections of code.
  1. Update comments regularly:
    • Keep comments up-to-date with code changes to avoid confusion.
  1. Avoid redundant comments.
    • Write comments that add value; avoid stating the obvious.
  2. Use proper grammar and punctuation.
    • Treat comments as a form of communication; use proper grammar and punctuation.

Types of comments:

  1. Single-line comments
  1. Multi-line comments
1. Single – line comment:
  • A single-line comment consists of only one line.
  • A single-line comment starts with the symbol hash # .
  • Single-line comments are used to give brief descriptions about specific lines of code.
  • Comments can also appear on the same line as code, following the statement they describe.
  • Developers can use single-line comments for quick debugging and testing purposes.

Syntax –

# Welcome to edSlash learning. 

Example –

				
					# This is a single-line comment
variable = 10  # Another comment on the same line
print(variable)

# Output on the screen
# 10
				
			
2. Multi – line comments –
  • There is no provision for multi-line comments in Python, like in other programming languages.
  • Multi-line comments are also called block comments.
  • It is useful when explanations extend over one line.
  • There are two ways to create multi-line comments:
    1. Multi-line comments with hashtags(#)

      Example –

      We can create multiple lines of comments using multiple hashtags by using # at the start of each line.

      Syntax –

      # Python block to illustrate

      # Multi-line comments with multiple hashatgs

				
					# This block of code is temporarily commented out.
# print("This won't be executed.")
# More code...
print('edSlash')

# Output -
# edSlash
				
			
  • 2. Multi-line comments using string literals-
    • We can create multiple line comments using string literals too.
    • We use a triple-quoted string (’’’ ‘’’,””” “””) to create multi-line comments.
    • Python ignores the string literals if they aren’t assigned to any variable and are not executed during the code’s execution.
    • A triple-quoted string provides easy syntax for creating multi-line blocks of text. This makes the code cleaner and more readable as compared to using a hash# at the beginning of each line.
    • Triple-quoted strings are also useful for creating a docstring of code.
    • It is important to note that using a hashtag(#) at the beginning of each line is a valid alternative to creating multi-line comments.

            Example –

    				
    					print('edSlash')
    '''
    This is a multi-line comment.
    It spans multiple lines without the need for # on each line.
    These lines are ignored by the Python interpreter during execution.
    '''
    print("working with multi-line comments")
    
    # Output -
    
    # edSlash
    # working with multi-line comments
    				
    			

    Example – Docstring using triple – quoted string

    				
    					def example_function(parameter):
        """
        This is a docstring for example_function.
    
        Parameters:
        - parameter: The input parameter for the function.
    
        Returns:
        - The result of some operation based on the input parameter.
        """
        # Function implementation goes here
        return result
    				
    			
    Advantages of Comments in Python

    1. Code Documentation:

    • Clear Explanation → Comments provide a narrative alongside the code, explaining its purpose and functionality. This is crucial for developers who might want to revisit the code later.
    • Understanding Complex Logic → In intricate sections of code, comments act as guides, breaking down complex logic into more digestible parts.

    2. Collaboration:

    • Communication among Team Members → In collaborative projects, comments act as a form of communication among team members. They facilitate understanding and cooperation, especially when multiple developers are working on the same codebase.
    • Knowledge Transfer → Comments help transfer knowledge about the codebase from experienced developers to beginners, smoothing the learning curve for the latter.

    3. Debugging:

    • Identifying Issues: → During debugging, comments can highlight potential issues or provide insights into the thought process behind certain decisions. This can expedite the debugging process.
    • Temporary Exclusions → Developers often use comments to temporarily exclude blocks of code for debugging purposes, allowing them to test different sections without deleting code.

    4. Readability:

    • Enhanced Readability → Well-placed comments contribute to code readability by offering context and explanations. This is especially beneficial for code maintainability over time.
    • Quick Scanning → Comments act as signposts, allowing developers to quickly scan through code and locate specific sections or functionalities.

    5. Future Maintenance:

    • Update Guidance → As code evolves, comments should be updated to reflect changes. This ensures that future maintainers have accurate information about the codebase.
    • Change Annotations → Comments can serve as annotations for planned changes or improvements, providing a roadmap for future development.

    6. Regulatory Compliance:

    • Legal and Regulatory Requirements → In certain industries, compliance with legal or regulatory requirements is crucial. Comments can be used to document compliance measures directly within the code.
    • Documentation for Audits → Comments can serve as documentation for audits, providing a clear record of decisions and actions taken in the code.

    Article written by Anurag Dubey, Team edSlash