Intensity Coding
  • HOME
  • TUTORIALS
    • Python
    • Natural Language Processing
  • ABOUT US
    • About Us
    • Contact Us
    • Privacy Policy
    • Terms and Conditions
    • Disclaimer

Python

Indentation And Comments in Python

Python
Python
  • Introduction To Python
  • Write Your First Python Program
  • Indentation And Comments in Python
  • Variables in Python
  • Data Types in Python
  • Booleans and Number in Python
  • Operators in Python
  • Mutable Vs Immutable Objects And Collection in Python
  • Python String
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Control Statements
  • Python Functions
  • Python Lambda Functions
  • Python Regular Expressions (RegEx)
  • Python JSON

IC_Python_Tutorial-3_Indentation_And_Comments_in_Python.png

Python Indentation¶

  • In Python, indentation refers to the spaces or tabs at the beginning of a code line.
  • Unlike in some other programming languages where indentation is primarily for readability, in Python, it serves a crucial role in code structure.
  • Python uses indentation to determine the grouping or block of code. This means that you must use consistent indentation within the same block of code. If you mix different levels of indentation, Python will raise an error.
In [ ]:
for i in range(5):
    # This code block is indented
    print(i)
# This code is not indented and is outside the loop
print("Loop finished")
0
1
2
3
4
Loop finished

Indentation Errors:

  • Incorrect indentation can lead to syntax errors in Python. Make sure that all lines within the same block have the same level of indentation.
In [ ]:
# Show Error
for i in range(5):
# This code block is indented
print(i)
# This code is not indented and is outside the loop
print("Loop finished")
  File "<ipython-input-2-e4dca2376ce4>", line 4
    print(i)
    ^
IndentationError: expected an indented block after 'for' statement on line 2

Python Comments¶

  • Comments in Python are used to annotate and document your code.
  • They are not executed by the Python interpreter and serve as helpful notes to explain the purpose of code, provide context, or make it more readable.
  • In python comments start with a #, and Python will render the rest of the line as a comment.
  • Comments can be used to prevent execution when testing code.

Single-Line Comments:¶

  • Single-line comments begin with the # symbol and continue until the end of the line.
In [ ]:
# This is a single-line comment
print("Intensity Coding")  # You can also place a comment at the end of a line of code
Intensity Coding
In [ ]:
# This line of code is commented out
# variable = 42  # You can comment out code like this

Multi-Line Comments:¶

  • To create a multiline comment in Python, you can either use the # symbol at the beginning of each line for multiple lines of comments, or you can use a multiline string.

  • While Python doesn't have a built-in syntax for multi-line comments like some other languages, you can use triple-quoted strings (single or double quotes) as a workaround.

  • When using a multiline string as a comment, as long as the string is not assigned to a variable or used in any way, Python will read it as code but then ignore it, effectively treating it as a multiline comment.

In [ ]:
#This is a comment
#written in
#more than just one line
In [ ]:
'''
This is a multi-line comment.
It spans multiple lines but is treated as a string.
'''
Out[ ]:
'\nThis is a multi-line comment.\nIt spans multiple lines but is treated as a string.\n'

Docstrings:¶

  • Docstrings are special comments used to document functions, modules, classes, or methods. They are enclosed in triple-quotes and are more structured than regular comments. The docstring is then made available via the doc attribute.
In [ ]:
def my_function(arg1, arg2):
    """
    This is a docstring.
    It provides detailed documentation for the function.
    """
    return arg1+arg2

print(my_function.__doc__)
    This is a docstring.
    It provides detailed documentation for the function.
    

Python Multiple Statements on a Single Line¶

  • In Python, you can put multiple statements on a single line by separating them with semicolons (;). This is sometimes referred to as "semicolon separation." However, it's important to use this feature judiciously because it can reduce code readability if overused.
statement1; statement2; statement3
In [ ]:
x = 5; y = 10; z = x + y

Python Multi-Line Statements in Python¶

  • In Python, statements typically end with a new line, but there are scenarios where you might need to continue a statement onto the next line. Python provides a line continuation mechanism using the backslash character (\) for this purpose. Here are two common situations where you might use the line continuation character:

Long Lines of Code:

  • When a line of code is too long to fit comfortably within the recommended line length limit you can use the line continuation character to split the statement across multiple lines.
  • This is often used for assignments, expressions, or function calls.
  • The backslash tells Python that the statement continues on the next line, effectively treating it as a single logical line of code.
total = item_one + \
        item_two + \
        item_three

Statements within Brackets:

  • When you have statements contained within square brackets [], curly braces {}, or parentheses (), you don't need to use the line continuation character. Python understands that the statement continues until the closing bracket, and the line break is considered part of the statement.
num1 = ['1', '2', '3',
        '4', '5']
  • In this example, the list elements are enclosed in square brackets, so Python knows that the list definition continues until the closing bracket.

Python Quotations¶

  • In Python, quotations, also known as quotation marks or string delimiters, are used to define and create strings, which are sequences of characters.

  • Single Quotes (' '): Strings can be enclosed within single quotation marks. Single quotes can be useful when your string contains double quotes.

  • Double Quotes (" "): Strings can also be enclosed within double quotation marks. Double quotes can be useful when your string contains single quotes.

In [ ]:
single_quoted_string = 'This is a single-quoted string.'
double_quoted_string = "This is a double-quoted string."
  • In addition to these basic quotations, Python also supports triple-quoted strings. Triple quotes (either single or double) are used to create multi-line strings or to include special characters within a string without escaping them.

Triple Single Quotes (''' '''):

In [ ]:
multiline_string = '''This is a
multi-line
string.'''

Triple Double Quotes (""" """):

In [ ]:
another_multiline_string = """This is another
multi-line
string."""
  • Using triple quotes is particularly useful when dealing with long strings, docstrings (used for documentation), or strings that span multiple lines.
Category
Python Natural Language Processing
Tag's
Python Natural Language Processing

Quick Links

  • Home
  • Tutorials
  • About Us
  • Contact Us

Tutorials

  • Python
  • Natural Language Processing

Tag's

  • Python
  • Natural Language Processing

About Intensity Coding

  • Intensity Coding is your learning hub for Data Science, Machine Learning, Deep Learning, NLP, and Generative AI. From beginner to expert level, we offer clear tutorials, real-world examples, and up-to-date insights. Our content simplifies complex topics to help you grow in your AI journey.
Intensity Coding

© 2025 Intensity Coding. All Rights Reserved.

Privacy Policy Terms and Conditions Disclaimer