DEV Community

Cover image for Want to Become a Python Developer? Indentation Matters!
Megalraja
Megalraja

Posted on

Want to Become a Python Developer? Indentation Matters!

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!")
Enter fullscreen mode Exit fullscreen mode

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!")
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

But Python uses indentation instead.

if 10 > 5:
    print("Hello")
Enter fullscreen mode Exit fullscreen mode

Where do we use indentation?

We use indentation in:

1. If conditions

if True:
    print("Correct")
Enter fullscreen mode Exit fullscreen mode

2. Loops

for i in range(5):
    print(i)
Enter fullscreen mode Exit fullscreen mode

3. Functions

def greet():
    print("Welcome!")
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

Can you fix it?

Top comments (0)