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

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence