Statement, Indentation and Comment in Python

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to learn about the statement, indentation, and comments in Python. Let's see all of them one by one.

Statement

The instructions written in Python are called statements. Let's see the following program.

Example

 Live Demo

print('Tutorialspoint') # statment

Output

If you run the above code, then you will get the following result.

Tutorialspoint

The one line that was written in the program is called statement. Every line in the program is a statement. Can't we write a multi-line statement? Why not, we can.

We can write the multi-line statements using the backslash (\).

Let's see how to write multi-line statements in Python.

Example

 Live Demo

# multi-line statement
   result = 2 + 3 * \
   5 - 5 + 6 - \
   3 + 4
print(result)

Output

If you run the above code, then you will get the following result.

19

Indentation

Before talking about the indentation, let's see what is a block. A block is a set of statements instructions. Other programming languages like C, C++, Java, etc.., uses {} to define a block.But Python uses indentation to define a block.

So, how to write an indentation. There is nothing more than a tab. Each statement in the block must start at the same level.

Example

def find_me():
   sample = 4
   return sample
find_me()

Output

If you run the above code, then you will get the following result.

4

Example

 Live Demo

def find_me():
   sample = 4
return sample
find_me()

Output

If you run the above code, then you will get the following error as output.

File "<tokenize>", line 3
   return sample
   ^
IndentationError: unindent does not match any outer indentation level

In the second program, the indentation level is not correct in the function block. So, we got an error. We must follow the indentation in Python. We can use the tab by default for indentation.

Comments

In Python, comments starts with hash (#) symbol. Let's see an example.

Example

 Live Demo

# This is a comment
# This too...
   a = 4
   # a = 5
print(a)

Output

If you run the above code, then you will get the following result.

4

Unlike many other programming languages, there is no support for multi-line comments in Python. But, most of the people use docstrings as multi-line comments which is not a good practice.

Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

raja
Published on 11-Jul-2020 07:02:24
Advertisements