the statements within a block line up vertically. So, how does it work? All statements with the same distance to the right belong to the same block of code, i.e. This principle makes it easier to read and understand other people's Python code. Okay that's what we expect from any program code, isn't it? Yes, but in the case of Python it's a language requirement, not a matter of style.
#Python indent block of code code#
code blocks are defined by their indentation. Python programs get structured through indentation, i.e. Please, keep this in mind to understand the advantages of Python!Įnjoying this page? We offer live Python training courses covering the content of this site. Programming languages, such as ALGOL, Pascal, and others, usually use certain methods to group statements into blocks:Ī code snippet in Pascal to show this usage of blocks: with ptoNode^ doīraces (also called curly brackets): tangled and inscrutable control structures.īlock structures were first formalized in ALGOL as a compound statement. Programmers had to rely on "go to" structures, nowadays frowned upon, because "Go to programs" turn easily into spaghetti code, i.e. Initially, in simple languages like Basic and Fortran, there was no way of explicitly using block structures. In many cases, it also serves as a way to limit the lexical scope of variables and functions.
A block in a script or program functions as a means to group statements to be treated as if they were one statement.
Generally, blocks can contain blocks as well, so we get a nested block structure. A language which allows grouping with blocks, is called a block structured language. Usually, it consists of at least one statement and declarations for the block, depending on the programming or scripting language. A block is a group of statements in a program or script.