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
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.
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules