What is Indentation and Why is it Important?
Indentation
refers to spacing the beginning of a line of code to the right by a certain amount.
In most programming languages, indentation is encouraged to make the code look neat and organized. However, in Python, incorrect indentation can cause your program to throw errors, making it crucially important.
Code Blocks and Indentation
In programming, a Code Block
refers to a group of lines that are executed together.
Code blocks are mainly used in functions, conditionals, loops, etc., grouping logically related code for execution.
While many languages use curly braces { }
to define code blocks, Python uses indentation.
// Function to add a and b
function add(a, b) {
return a + b;
}
# Function to add a and b
def add(a, b):
return a + b
How to Use Indentation
Indentation in Conditionals
if condition:
print("Executed if the condition is true") # Indented
else:
print("Executed if the condition is false") # Indented
In the example above, if the if
condition is true, the indented print
statement will execute.
If there's a mistake in indentation, the program will not function as intended.
if condition:
# No indentation, error occurs
print("Executed if the condition is true.")
Indentation in Loops
for i in range(3):
print(i) # Indented
In the example above, the for
loop executes print
statements for each value returned by range(3)
from 0 to 2.
Without indentation on the print
statement, the loop will not function correctly.
for i in range(3):
print(i) # No indentation, error occurs
Indentation in Functions
def add(a, b):
result = a + b # Indentation defines the function body
return result # Indentation specifies the return value
result = add(3, 5)
In the example above, the add
function accepts two parameters (a
, b
) and returns their sum.
An argument is a value provided to a function to perform its task.
In the code, the function add
receives 3 for a
and 5 for b
, and the variable result
will store the returned value, which is 8.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.