0% found this document useful (0 votes)
16 views5 pages

Python Statements, Indentation, Comments

This tutorial covers Python statements, the significance of indentation, and the use of comments in programming. It explains how to create multi-line statements, the importance of consistent indentation for code readability, and how comments and docstrings enhance code understanding. The document also provides examples of single-line and multi-line comments, as well as the use of triple quotes for docstrings.

Uploaded by

irshadrayn2414
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views5 pages

Python Statements, Indentation, Comments

This tutorial covers Python statements, the significance of indentation, and the use of comments in programming. It explains how to create multi-line statements, the importance of consistent indentation for code readability, and how comments and docstrings enhance code understanding. The document also provides examples of single-line and multi-line comments, as well as the use of triple quotes for docstrings.

Uploaded by

irshadrayn2414
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Statement, Indentation and

Comments
In this tutorial, you will learn about Python statements, why indentation is
important and use of comments in programming.

Python Statement
Instructions that a Python interpreter can execute are called statements.
For example, a = 1 is an assignment
statement. if statement, for statement, while statement, etc. are other kinds
of statements which will be discussed later.
Multi-line statement

In Python, the end of a statement is marked by a newline character. But we


can make a statement extend over multiple lines with the line continuation
character (\). For example:

a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9

This is an explicit line continuation. In Python, line continuation is implied


inside parentheses ( ), brackets [ ], and braces { }. For instance, we can
implement the above multi-line statement as:

a = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)

Here, the surrounding parentheses ( ) do the line continuation implicitly.


Same is the case with [ ] and { }. For example:

colors = ['red',
'blue',
'green']

We can also put multiple statements in a single line using semicolons, as


follows:

a = 1; b = 2; c = 3

Python Indentation
Most of the programming languages like C, C++, and Java use braces {

} to define a block of code. Python, however, uses indentation.


A code block (body of a function, loop, etc.) starts with indentation and
ends with the first unindented line. The amount of indentation is up to you,
but it must be consistent throughout that block.
Generally, four whitespaces are used for indentation and are preferred over
tabs. Here is an example.

for i in range(1,11):
print(i)
if i == 5:
break

The enforcement of indentation in Python makes the code look neat and
clean. This results in Python programs that look similar and consistent.

Indentation can be ignored in line continuation, but it's always a good idea
to indent. It makes the code more readable. For example:

if True:
print('Hello')
a = 5

and
if True: print('Hello'); a = 5

both are valid and do the same thing, but the former style is clearer.

Incorrect indentation will result in IndentationError .

Python Comments
Comments are very important while writing a program. They describe what
is going on inside a program, so that a person looking at the source code
does not have a hard time figuring it out.

You might forget the key details of the program you just wrote in a month's
time. So taking the time to explain these concepts in the form of comments
is always fruitful.

In Python, we use the hash (#) symbol to start writing a comment.


It extends up to the newline character. Comments are for programmers to
better understand a program. Python Interpreter ignores comments.

#This is a comment
#print out Hello
print('Hello')

Multi-line comments

We can have comments that extend up to multiple lines. One way is to use
the hash(#) symbol at the beginning of each line. For example:

#This is a long comment


#and it extends
#to multiple lines

Another way of doing this is to use triple quotes, either ''' or """ .

These triple quotes are generally used for multi-line strings. But they can
be used as a multi-line comment as well. Unless they are not docstrings,
they do not generate any extra code.

"""This is also a
perfect example of
multi-line comments"""

Docstrings in Python

A docstring is short for documentation string.

Python docstrings (documentation strings) are the string literals that appear
right after the definition of a function, method, class, or module.
Triple quotes are used while writing docstrings. For example:

def double(num):
"""Function to double the value"""
return 2*num

Docstrings appear right after the definition of a function, class, or a module.


This separates docstrings from multiline comments using triple quotes.

The docstrings are associated with the object as their __doc__ attribute.
So, we can access the docstrings of the above function with the following
lines of code:

def double(num):
"""Function to double the value"""
return 2*num
print(double.__doc__)
Output

Function to double the value

Common questions

Powered by AI

The recommended practice for using comments in Python includes using the hash (#) symbol to explain complex sections of code or logic, background information, and any non-obvious aspects of the code. Comments should be concise and relevant, avoiding unnecessary verbosity. Good commenting enhances code maintainability by making it easier for other programmers, or the author at a later time, to understand the program's function and logic, which is especially important in large or collaborative projects . Providing clear explanations helps ensure that the code can be modified or debugged effectively over time.

Comments and docstrings in Python serve different purposes. Comments, initiated by a hash (#) symbol, are used to annotate code, helping a programmer understand the logic and intent of the written program. These are not processed by the Python interpreter . Docstrings, on the other hand, are string literals that appear immediately after a function, class, or module definition, and are used for documentation purposes to describe what the code does . Unlike regular comments, docstrings can be accessed programmatically via the __doc__ attribute, allowing them to provide runtime documentation . While both enhance code understandability, docstrings offer a more formal and standardized documentation approach.

In Python, multiple statements can be included on a single line by using semicolons to separate each statement, such as in 'a = 1; b = 2; c = 3' . The advantage of this structure is that it can make code more compact and reduce the number of lines. However, this method should be used sparingly as it can reduce readability and clarity of the code compared to having one statement per line.

Indentation in Python signifies the start of a block of code and the end is marked by the first unindented line, thereby replacing braces used in languages like C++ or Java . This method makes Python code more consistent and clean, enforcing a standardized format across different scripts. In contrast, C++ and Java use braces to define code blocks, which allows more flexibility in formatting but can lead to inconsistencies in code appearance.

The benefit of implicit line continuation with parentheses, brackets, or braces in Python is that it creates more readable and clean code by reducing the need for visual clutter like backslashes . These symbols naturally indicate continuation of calculations or data structures, enhancing clarity particularly in complex expressions or configurations. However, a potential challenge is that implicit line continuation relies on understanding context where parentheses or similar symbols are appropriate. In contrast, explicit continuation via backslashes can sometimes be more recognizable, especially for those familiar with languages that frequently use explicit markers. Ultimately, while implicit line continuation reduces syntactic noise, it demands careful use of syntax to avoid inadvertent errors.

In Python, multi-line statements allow a single logical code statement to span multiple lines. This can be achieved explicitly using the line continuation character (\), or implicitly within parentheses (), brackets [], and braces {}. Implicit line continuation is particularly useful as it allows for cleaner and more readable code by removing the need for explicit continuation characters. For example, a multi-line statement can be written using parentheses: 'a = (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9)' without the need for a backslash to indicate continuation . This method supports writing long expressions and data constructs more clearly and readably.

Incorrect indentation in Python leads to an IndentationError, preventing the code from running. Since Python relies on indentation to define scope and separate different code blocks, any inconsistency in indentation levels can cause logical errors or runtime exceptions . In contrast, languages like C++ or Java use braces to define blocks, meaning that indentation primarily affects readability and has no bearing on code execution. Therefore, while improper indentation in Python can cause the code to fail completely, in brace-using languages, it primarily affects developer productivity by reducing code clarity.

Block comments in Python use the hash (#) symbol at the beginning of each line to comment out an entire block of code or provide a detailed explanation above a section of code. They are used to describe large sections, provide context, or offer extended explanations . Inline comments, placed on the same line as a statement after a hash (#), are used for brief clarifications of code logic or specific operations within a single line, such as 'x = x + 1 # increment x by 1'. Inline comments should not be overused, as they can clutter the code, but are useful for explaining complex statements or decisions.

Python's handling of statements, which do not require terminators like semicolons, and its use of indentation, enhance code readability by ensuring a uniform and uncluttered visual representation of code . This indentation-reliant structure eliminates errors associated with misplaced braces commonly seen in languages like C++ or Java. Readability, in turn, improves developer efficiency by making Python code easier to understand and debug, fostering quicker development cycles. However, Python's strict indentation can potentially cause runtime errors if code blocks are not correctly aligned, requiring developers to be cautious yet encourages a disciplined coding style that ultimately benefits long-term project maintenance and collaboration.

Triple quote strings, denoted by ''' or ", can serve dual purposes in Python. For documentation, they are used as docstrings to describe modules, classes, or functions immediately after their declaration, such as: 'def double(num): """Function to double the value""" return 2*num' . They are associated with the function or module as a __doc__ attribute, used for generating documentation. As multi-line comments, they provide a convenient way to comment out blocks of code temporarily or add extended comments without interfering with code logic: """This is a multi-line comment""" . However, unlike comments, these strings are parsed as literals and can execute under certain situations unless ignored by treating them solely as comments.

You might also like