What Do We Use to Define a Block of Code in Python Language?

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning

Indentation is used to define a block of code in python. Braces {} are used to define a block of code in most programming languages, like C, C++, and Java. But this indentation makes python unique among all programming languages.

This indentation highlights the block of code. In Python, indentation is done with whitespace. All statements with the same right-hand distance belong to the same code block. If a block needs to be more nested, it is indented to the right.

Indentation is only used in most other programming languages to help make the code look nice. However, it is required in Python to indicate which block of code a statement belongs to.

Examples of Python Programs Showing use of Indentation

Name checking if-else program is given to better understand an indentation in python. Looking at the code below will help you understand the concept of an indentation in python in a much better way.

Example 1: Program for Checking names using Python

Output:

Explanation:

There are two separate code blocks in print('Correct Name!!') and print('InCorrect Name:('). In our example if-statement, the two code blocks are both four spaces indented. Now we can see that print("HI") is not intended, hence print("HI") will not be the part of else block.

Example 2: Showcasing use of Indentation in Python using loop

Code:

Output

Explanation:

In Python, each line of a code block must be indented by the same amount of whitespace. The while loop's two lines of code are both four spaces indented. A statement must be labeled with the code block to which it belongs.

For example, i=1 and while (i=4) are not indented and thus do not belong in the while block. Python code is structured using indentation.

If indentation is not properly added, code will throw a compilation error. Indentation has to be properly added. The next Section has some indentation articles for reference

Learn More

Conclusion

  • In Python, defining a block of code becomes easy because of the concept of indentation.
  • In Python, each line of code block must be indented by the same amount of whitespace.
  • Python code becomes well-formatted when indentation is used.