Indentation in Python¶
- 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.
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.
# 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
Comments in Python¶
- 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.
# 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
# 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.
#This is a comment
#written in
#more than just one line
'''
This is a multi-line comment.
It spans multiple lines but is treated as a string.
'''
'\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.
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.
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
x = 5; y = 10; z = x + y
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.
Quotations in Python¶
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.
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 (''' '''):
multiline_string = '''This is a
multi-line
string.'''
Triple Double Quotes (""" """):
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.