Python Introduction | Statements | Relationship Between Statements and Indentation

Relationship Between Statements and Indentation

Values and operations are fundamental to programming languages. Another important concept is control.

Executing commands only in order supports a limited set of programs. More complex programs control their flow according to the situation, such as executing a process only under certain conditions or repeating it a specified number of times.

Statements provide instructions for controlling program behavior. Statements designed to control the flow of a program are called control statements.

Python syntax has a distinctive feature: indentation. Indentation moves the beginning of a line to the right with spaces or tabs.

Python uses indentation to define blocks in many statements. If a statement means “perform the following process in this case,” the process is indented to the right. Lines at that indentation level belong to the statement.

To finish the block, return the indentation to its previous position. Python recognizes the statement to which a line belongs based on where the line begins.

The following outline illustrates this structure.

Writing Python Statements

ordinary statement ......
statement 1
     process for statement 1 ......
     process for statement 1 ......
     nested statement inside statement 1
         process for the nested statement ......
         process for the nested statement ......
     process for statement 1 ......
statement 2
     process for statement 2 ......
ordinary statement
ordinary statement
...... omitted ......

Statements are structured by changing the starting position of each line. Incorrect indentation can cause a syntax error.

Python code generally uses spaces instead of tabs for indentation. The exact width is not part of the syntax, but four spaces are widely used. Consistency is important.

If indentation is too narrow, the structure becomes difficult to read and mistakes become easier to make. If it is too wide, lines quickly move far to the right. Choose a practical width and apply it consistently.