Indentation in Python

Indentation is a critical component of code development in Python.

It must be used for the code to execute correctly.

Overview

Unlike many other programming languages Python will pay attention to the way the code is indented. For comparison a code statement in R is defined by curly braces. For example, in the R code below the braces indicate the bounds of the if statement:

my_val <- TRUE
if (my_val) {
    print("This is inside the brackets.")
    print("Theses statements will be evaluated if my_val is TRUE.")
}

print("This is no longer inside the bounds of the if statement.")

In Python, the equivalent code would be:

my_val = True
if my_val:
    print("Where'd the brackets go!?!")
    print("These would still be evaluated as long as my_val is True.")

print("This is no longer part of the if statement.")

As you can see, there are no curly braces to indicate the bounds of the statement. Instead, the level of indentation is uses. This applies for loop logic as well:

values = [1, 2, 3, 4, 5]
for v in values:
    print(f"v: {v}")

Code Output:

v: 1
v: 2
v: 3
v: 4
v: 5

Python cares when and where you indent. Be sure to pay attention to this while writing code!