Course

Python Code Block: Syntax, Usage, and Examples

In Python, a code block is a segment of code that belongs together and shares the same indentation level.

How to Use a Code Block in Python

Python uses indentation to define blocks of code. Each code block starts with an indentation and ends when the indentation level returns to a previous level.

python
if True: print("This is inside a code block.") print("This is outside the code block.")

When to Use Code Blocks in Python

Code blocks are essential in Python programs of any kind for defining the scope of control structures, functions, and loops. They help organize code into manageable segments.

If Statements

In if statements or other conditional statements, code blocks define the lines of code to execute when conditions evaluate to True.

python
age = 20 if age >= 18: print("Adult") # This is a code block else: print("Minor") # This is another code block

Functions

Every Python function uses a code block to contain its operations.

python
def greet(): print("Hello, welcome!") # Function's code block

Loops

For loops execute code blocks as long as there are items in a sequence to iterate over. While loops execute code blocks as long as a specified condition is true.

python
for i in range(5): print(i) # Loop's code block

Examples of Code Blocks in Python

Nested If Statements

Code blocks can exist within other blocks. As an example, consider nested if statements.

python
x = 10 if x > 5: print("x is greater than 5") if x % 2 == 0: print("x is even") # Nested code block

Multiple Operations in Loops

Loops often feature multiple operations within their code blocks, executing more than one action per iteration.

python
for i in range(3): print(i) print(i*2) # Multiple statements in a loop's code block

Learn More About Code Blocks in Python

Importance of Indentation

Other programming languages use indentation only for readability. Code in Python, however, needs proper indentation to identify blocks of code. Incorrect indentation can lead to errors or unintended behavior.

python
if True: print("Incorrect indentation") # Causes IndentationError