In Python, code block refers to a collection of code that is in the same block or indent. This is most commonly found in classes, functions, and loops.
You can where code blocks are because they are 1) on the same indent and 2) are uninterrupted by other lines of code not on the same indent.
Python code blocks are useful because they tell you what pieces of code will run as a part of a loop, class, or function.
def code_block(): # Everything in this function is part of the same code block print (1) print (2) for i in range(4): # Everyting in this loop is part of the same code block print (i)
However, the function and the loop are parts of different code blocks!
Let’s take a look at a python assign a variable code sample
Python Code Block¶
A code block is a collection of code that sits on the same indent. Think of it like a line of code and it's cousins, brothers, or sisters.
Let's take a look at a few code blocks.
for i in range(4): print (i)
0 1 2 3
for i in range(4): print (i) print (i * 2)
0 0 1 2 2 4 3 6
All the code that sits within a function is also a code block
def my_code(): x = 5 # same block x = x + 4 # same block print (x) # same block my_code() # Not on the same block of code as above
Check out more Python Vocabulary on our Glossary Page