Python Indentation
๐ง Python Indentation (very important in Python)
In Python, indentation is not optional—it defines the structure of your code (instead of {} like in Java/C++).
What is indentation?
Indentation means spaces at the beginning of a line.
Python uses indentation to define blocks of code (like inside if, for, functions, etc.).
๐ Rules of indentation
- Use 4 spaces (standard practice)
- Be consistent (don’t mix tabs and spaces)
- All lines in same block must have same indentation
๐ง Simple understanding
- Tab = shortcut key for indentation
- Spaces = actual characters (recommended in Python)
๐น Basic Example
if True:
print("Hello") # indented → inside if block
print("Outside") # not indented → outside block
❌ Wrong (will give error)
if True:
print("Hello") # ❌ no indentation
๐ Error: IndentationError
๐น Example with loop
for i in range(3):
print(i)
print("Loop running")
print("Done")
๐น Nested indentation
if True:
print("Level 1")
if True:
print("Level 2")
⚠️ Common mistakes
1. Mixing tabs & spaces
if True:
print("Hello") # tab
print("World") # spaces ❌
2. Wrong alignment
if True:
print("Hello")
print("World") # ❌ mismatch
๐ก Tip
Most editors (like VS Code, PyCharm) auto-indent for you ๐
๐งช Real Example (Function)def greet ():
print("Hi")
print("Welcome")
greet()
Comments
Post a Comment