Python indentation
Table of Contents
Description
Indentation and code blocks in Python are used to define the structure and flow of control. Unlike many other programming languages that use braces {} or keywords to define code blocks, Python uses whitespace indentation. A consistent number of spaces or tabs must be used to indicate the start and end of code blocks such as if, for, while, def, and class.
Incorrect indentation leads to syntax errors and improper logic execution.
Prerequisites
- Basic knowledge of Python syntax.
- Familiarity with control structures (if, for, while).
- Awareness of Python being whitespace-sensitive.
Examples
Here's a simple program in Python:
Correct Indentation:
python def greet(): print("Hello") if True: print("Inside If Block") greet() Incorrect Indentation (Throws Error): python def greet(): print("Hello") # ❌ IndentationError Mixed Tabs and Spaces (Bad Practice): python def greet(): ↹print("Hello") # Tab ··print("Hi") # Spaces (Leads to error)Real-World Applications
Writing clean and readable code.
Avoiding logic errors in nested conditions and loops.
Maintaining consistency in large codebases and collaborative projects.
Auto-formatting tools (like Black, Flake8) depend on proper indentation.Where topic Can Be Applied
All Python scripts and programs: Every Python developer must follow indentation rules.
Educational environments: Teaching Python basics starts with understanding indentation.
Code editors and IDEs: Tools like VS Code, PyCharm help auto-indent.
Collaborative projects: Teams use linters to ensure uniform indentation.
Resources
WatchTopic video source
A comprehensive video
VisitPython pdf
pdf on topic
Interview Questions
Why is indentation important in Python?
What is the default indentation level in Python?
What happens if you mix tabs and spaces in Python?
How does indentation affect the flow of a Python program?
Can you give an example where incorrect indentation caused a logic error?