Python Tutorial 0/52 lessons ~6 min read Lesson 5
Syntax & Indentation
Python uses indentation, not braces, to define code blocks.
Course progress0%
Focus
9 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
Introduction
Python uses indentation, not braces, to define code blocks. This forces consistent formatting and is one of the most distinctive features of the language.
Understanding the topic
Core concepts to understand:
- 4 spaces per indent (PEP 8).
- Colons start blocks:
if,for,def,class. - Comments use
#; docstrings use"""...""". - Statements end at line break — no semicolons.
Syntax reference
Visual flow / code:
python
def factorial(n: int) -> int:"""Return n! using recursion."""if n <= 1:return 1return n * factorial(n - 1)# Multi-line: use parens or backslashtotal = (1 + 2 + 3+ 4 + 5)
Execution workflow
1Python Syntax & Indentation Workflow
1 / 44 spaces per indent (PEP 8)
4 spaces per indent (PEP 8).
Real-world use
Indentation-based syntax is divisive but enforces readable code — there's only one way to format a block, which kills bikeshedding in code reviews.
Best practices
- Always 4 spaces, never tabs.
- Configure your editor for PEP 8.
- Add docstrings to public functions.
Common mistakes
- Mixing tabs and spaces — Python 3 errors out.
- Inconsistent indent depth.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhy does Python use indentation?+
Answer
Python uses indentation to mark blocks so that the visual structure of the code is the same as its logical structure, which removes braces and the chance of them disagreeing with indentation. The tokenizer turns increases and decreases in indentation into INDENT and DEDENT tokens that the parser treats like block delimiters. The trade-off is that whitespace errors become syntax errors.
Follow-up
What error do you get for inconsistent indentation?
2BeginnerQuestionWhat's PEP 8?+
Answer
PEP 8 is the official style guide for Python code, covering naming (
snake_case for functions, CapWords for classes), 4-space indentation, line length of 79 characters, imports, and whitespace. It is a convention that improves consistency rather than a language rule. Teams usually enforce it with tools such as ruff, flake8, or a formatter like black.Follow-up
Which tools do you use to enforce it automatically?
3BeginnerQuestionTabs vs spaces?+
Answer
PEP 8 recommends 4 spaces per indentation level, and spaces are the common convention. Python 3 does not allow ambiguous mixing: if tabs and spaces are mixed in a way that makes block structure depend on tab width, it raises
TabError. Tabs are still legal if used consistently, but pick one and configure your editor and formatter to match.Summary
In summary: Indentation defines structure. PEP 8 = community style law.
Ready to mark this lesson complete?Track your journey across the entire course.