Indentation and Comments in Python (Part 2)

Posted by

1.Indentation in Python

  • In Python, indentation refers to the spaces at the beginning of a code line.
  • Unlike many other programming languages, indentation in Python is crucial and not just for readability. It is used to define code blocks.
  • Python uses indentation to indicate which statements belong to a particular block of code. All the statements indented at the same level are considered part of the same block.
  • Indentation level can be increased to create nested blocks.
  • The number of spaces used for indentation is up to the programmer, as long as it’s consistent within the same block. Using at least one space is mandatory.
  • It is recommended to use the same number of spaces for all lines in the same block to improve code readability.

highlighted is indentation

2.Comments in Python

  • Single line comments: These comments start with the hash symbol (#) and extend to the end of the line. They are used for short explanations about the code.
# This is a single line comment

  • Multiline comments: Python doesn’t have a dedicated way to write multiline comments, but there are two workarounds:
    • Using multiple lines that each begin with a hash symbol (#).

# This is a multiline comment
# created using multiple hash symbols

* Using triple quoted strings (either three single quotes or three double quotes).  These are not technically comments, but the Python interpreter will ignore them.

"""This is a multiline comment
created using triple quoted strings"""

  • Docstrings: These are special multiline comments used to document functions, classes, and modules. Docstrings are typically placed within triple quotes directly below the function or class definition. They provide information about the function or class’s purpose, usage, and parameters.

def greet(name):
  """
  This function greets the user by name.

  Args:
      name: The name of the person to greet.

  Returns:
      A string containing the greeting message.
  """
  return f"Hello, {name}!"

print(greet("Alice"))

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x