When learning Python, you will learn variables, conditions, loops, and functions.
But there is one important thing you should understand: Indentation.
What is indentation?
Indentation means adding spaces at the beginning of a line.
Example:
if 10 > 5:
print("Hello Python!")
Notice the spaces before print().
These spaces tell Python that the print() statement belongs inside the if condition.
What happens if we don't use indentation?
if 10 > 5:
print("Hello Python!")
This code gives an IndentationError.
Why? Because Python expects spaces before the code inside the if condition.
Why is indentation important?
In Java, we use curly braces {} to separate code blocks.
if (10 > 5) {
System.out.println("Hello");
}
But Python uses indentation instead.
if 10 > 5:
print("Hello")
Where do we use indentation?
We use indentation in:
1. If conditions
if True:
print("Correct")
2. Loops
for i in range(5):
print(i)
3. Functions
def greet():
print("Welcome!")
Tips to remember
- Use 4 spaces for each indentation level.
- Keep statements in the same block aligned.
- Don't mix tabs and spaces.
- Check indentation when you get an error.
Try this challenge!
Find the mistake in this code:
if 10 > 5:
print("Hello")
print("Python")
Can you fix it?
Top comments (0)