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.
Learn Python on Mimo
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
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot