Compound statements are high-level control structures that allow you to group multiple statements together to perform more complex tasks or define the structure of your code. We have already talked about two of these structures: conditional statements (if, elif, else) and loop statements (for and while). In upcoming lessons, we will explore various other compound statements, including function definitions (def), class definitions (class), and the concept of exception handling (try and except).

When using compound statements in the Python interpreter interactively, there are several things you need to keep in mind. The interpreter uses indentation to define the scope of these statements, and the code is executed as you enter it. The >>> prompt indicates that you can enter multiple lines of code as part of the same compound statement. Proper indentation is crucial in the Python interpreter to ensure that the code is correctly structured.

Importance of indentation

Python relies on indentation to define the scope of compound statements. Indentation should be consistent and typically consists of four spaces per level. Avoid mixing tabs and spaces for indentation, as this can lead to errors. For instance, if you start indenting with spaces, continue with spaces throughout the block.

>>> x = 10
>>> if x > 5:
... print("x is greater than 5")
... else:
... print("x is not greater than 5")
...
x is greater than 5

In this example, the if statement and its associated code blocks are properly indented, allowing the Python interpreter to understand the scope and structure.

Using colons

Python uses colons (:) to indicate the start of a compound statement. After the colon, you should begin the indented block of code. This is true for all compound statements, such as if, for, while, def, and class.

>>> for i in range(3):
... print(i)
...
0
1
2

The colon after for i in range(3) signifies that the following indented lines are part of the loop body.

Maintaining block structure

Ensure that the statements within a compound statement are correctly indented to form a coherent block of code. All statements at the same level of indentation are considered part of the same block.

$ python
>>> if x > 5:
... print("x is greater than 5")
... y = x * 2
... print(f"y is {y}")
...
x is greater than 5
y is 20

Here, the lines printing x and y and the assignment of y are all part of the same block due to their consistent indentation.

Working in interactive mode

The Python interpreter is an interactive environment, and it expects you to enter statements one at a time. You can continue a multiline statement or compound statement by entering a blank line, and the interpreter will continue until the block is complete.

>>> count = 0
>>> while count < 3:
... print(count)
... count += 1
...
0
1
2

The while loop continues to execute as long as the condition count < 3 is True, and each line within the loop body is properly indented.

Handling nested statements

If you are using nested compound statements (e.g., an if statement inside a for loop), make sure to maintain the proper level of indentation for each level of nesting.

>>> for i in range(3):
... if i % 2 == 0:
... print(f"{i} is even")
... else:
... print(f"{i} is odd")
...
0 is even
1 is odd
2 is even

In this example, the if statement is nested within the for loop, and the indentation reflects this structure.

Avoiding and detecting syntax errors

Be vigilant about syntax errors, as they can be more easily overlooked when entering code interactively. The interpreter will raise an error if there are syntax issues. Pay attention to the Python interactive prompts (>>> and ...). The >>> prompt indicates the start of a new statement, while the ... prompt means that the interpreter is continuing a multiline statement or compound statement.

>>> if x > 5:
... print("x is greater than 5")
File "", line 2
print("x is greater than 5")
^
IndentationError: expected an indented block

In this case, the lack of proper indentation after the if statement results in an IndentationError.

Practicing with compound statements

Here are a few examples that you can enter into your Python interpreter to familiarize yourself with the syntax of compound statements in interactive mode. Feel free to intentionally introduce errors to observe the types of error messages generated and gain familiarity with the debugging process (We will focus on this concept more in Lesson 7!). This hands-on approach will help you better understand how compound statements work in the Python shell.

Example of Conditional Statements

>>> x = 10
>>> if x > 5:
... print("x is greater than 5")
... else:
... print("x is not greater than 5")
...
x is greater than 5

Example of Loop Statement

>>> for i in range(3):
... print(i)
...
0
1
2

Example of Nested Statement

>>> for i in range(3):
... print(f"Outer loop iteration {i}")
... for j in range(1, 4):
... print(f" Inner loop iteration {j}")
...
Outer loop iteration 0
Inner loop iteration 1
Inner loop iteration 2
Inner loop iteration 3
Outer loop iteration 1
Inner loop iteration 1
Inner loop iteration 2
Inner loop iteration 3
Outer loop iteration 2
Inner loop iteration 1
Inner loop iteration 2
Inner loop iteration 3

In conclusion…

Understanding and using compound statements in the Python interpreter effectively requires attention to indentation, use of colons, and proper structuring of code blocks. The interactive nature of the Python shell makes it a powerful tool for testing and developing code in real-time. By practicing with examples and being mindful of common pitfalls, you can harness the full potential of compound statements to write clean, efficient, and well-structured Python code.