0
0
Pythonprogramming~5 mins

Python Block Structure and Indentation

Choose your learning style9 modes available
Introduction

Python uses indentation (spaces or tabs) to group code together. This helps the computer know which lines belong together in a block.

When writing functions to group the steps inside them.
When using if-else statements to decide what code runs.
When creating loops to repeat actions multiple times.
When organizing code inside classes or methods.
Syntax
Python
if condition:
    # indented block of code
    statement1
    statement2
# code here is outside the block
Indentation must be consistent: use the same number of spaces or tabs for each block.
Python does not use curly braces { } like some other languages; indentation shows blocks.
Examples
Both print statements run only if x is greater than 0 because they are indented under the if.
Python
if x > 0:
    print("Positive")
    print("Number")
The print(i) runs 3 times inside the loop. The print("Done") runs once after the loop because it is not indented.
Python
for i in range(3):
    print(i)
print("Done")
The two print lines are inside the function because they are indented. The greet() call runs the function.
Python
def greet():
    print("Hello")
    print("Welcome")
greet()
Sample Program

This program uses indentation to group code inside the function and inside the if-elif-else blocks. It prints messages based on the number.

Python
def check_number(num):
    if num > 0:
        print(f"{num} is positive")
    elif num == 0:
        print("Number is zero")
    else:
        print(f"{num} is negative")

check_number(5)
check_number(0)
check_number(-3)
OutputSuccess
Important Notes

Always use either spaces or tabs for indentation, never mix both in the same file.

Most editors can help by automatically indenting code for you.

Indentation errors cause Python to stop running and show an error message.

Summary

Python uses indentation to show which lines of code belong together.

Indentation must be consistent and is required for blocks like functions, loops, and conditionals.

Proper indentation makes your code easier to read and run correctly.