PYTHON

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.

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.

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.

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.

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.

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.

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.

if True:
print("Incorrect indentation")  # Causes IndentationError
Learn Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH