Editor settings

General settings

Save settings

Learn to program with Python

Code blocks in Python #

We can observe that there is an indentation under the function name when we define a new function. While indentation in other languages may be used for readability purposes, in Python, it plays a critical role in the code's operation.

Using whitespace or indentation to indent the code is a way to indicate to the code reader and the Python program that the code at this level belongs to the same group, or sometimes called the same code block. Each code block must have the same number of spaces or tabs, for example, the example below will use 4 spaces and 1 space for indentation.

def say_hi(): # Block 1
    print("Hello World!") # Block 2
    print("How is it going?") # Block 2

def say_hi_2(): # Block 1
 print("Hello World!!") # Block 2
 print("How is it going??") # Block 2

However, in code blocks at the same level, not using the same number of spaces or tabs to indent the code will cause the program to fail with an error IndentationError: unexpected indent. Therefore, it is important to pay attention to the code indentation in Python.

def do_something(): # Block 1
    print("Do this") # Block 2
        print("Do that") # Block 2
Modern code editors often have functions to help manage indentation, including online editors on our website. Everyone can use the Tab key to add 4 spaces, and sometimes the system will also automatically add spaces, such as when detecting a function definition.

Try typing the code example above in the editor and observe the automatic indentation.

Exercise #

  • Adjust the indentation in the function definition from 4 spaces to 2 spaces.
Output will be displayed here