Python Statements and Comments

Statements in Python are the block of codes. The instructions that a Python interpreter can execute are called the statements.

What is a statement in Python?

There are various kinds of statements like assignment statement that assigns values to a variable and other statements like control statements, loop statement etc. Python uses indentation to differentiate the statements.

Multi-line statement
The end of the statement is marked by a newline character in Python, however, we can make a statement extend over several lines with the line continuation character (\). We can also use parenthesis “()” or “[]” to extend variables over other lines. Let us see the following example where three variables are declared and assigned values using three different ways.

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

b = (4 + 1 + 3 +
    4 + 3 + 6 +
    7 + 5 + 2)

c = ['1',

We can also declare multiple variables in a single line using a semicolon (;).

x = 13; y = 'John'; d = 3

Lines and Indentation in Python

Most of the programming languages such as C, C++ or Java uses parenthesis “{}” to separate block of codes. But in Python, we use indentation with 4 spaces or a tab to differentiate a block from another. Blocks of code are denoted by line indentation, which is rigidly enforced.

Let us take an example of a basic if else statement

if True:

Comments in Python

Comments are useful in a program to provide that extra bit of information regarding the statements that are being written. A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them.

# This is a single line comment in python

How to write multiline comments in Python?

Python uses triple single quotes or triple double quotes to allow multiline comments.

# Using # in multiple lines can define multiline comments
#Multiline Comment 1
#Multiline Comment 2
#Multiline Comment 3

# Using triple single quotes for multiline comment
Multiline Comment 1
Multiline Comment 2
Multiline Comment 3

# Using triple double quotes for multiline comment
Multiline Comment 1
Multiline Comment 2
Multiline Comment 3

What is Docstring in Python?

Docstring in Python is used to define documentation for functions or classes that is the first statement in the function, class or module. We can write the proper function documentation in the docstring so that other user can read those comments and understand the meaning of the block of code. For writing docstring, we use triple quotes.

def sum(num1, num2):
    """Function to add two numbers and return the sum"""
    return num1 + num2
SHARE Python Statements and Comments

You may also like...

Leave a Reply

Your email address will not be published.