Skip to main content

Python Syntax & Indentation Rules

Launch Sprint · Day 5

Master Python syntax & indentation

Python's whitespace rules are simple but strict. Nail them now to avoid `IndentationError`s, keep your code readable, and align with PEP 8.

4

Spaces per indent

79/88 chars

Max line length

12 mins

Time

Python syntax pillars

  • Whitespace matters—blocks are defined by indentation, not braces.
  • Statements end implicitly; use backslashes or parentheses for multi-line expressions.
  • Comments use #; docstrings use triple quotes """.

Indentation rules

Correct indentationBEGINNER
def classify_score(score: int) -> str:
if score >= 90:
return "A"
elif score >= 80:
return "B"
else:
return "Keep going!"


students = ["Ava", "Liam", "Noah"]
for name in students:
print(name.upper())

Use 4 spaces per indent level. Never mix tabs and spaces.

Tips:

  • Configure your editor to insert spaces when pressing Tab.
  • Align wrapped expressions inside parentheses:
greeting = (
"Hello "
+ name.title()
+ "!"
)

Naming conventions

TypeConventionExample
Variables & functionssnake_casetotal_sales, calculate_tax()
ClassesPascalCaseclass ShoppingCart:
ConstantsUPPER_SNAKE_CASEMAX_RETRIES = 3

Comments & docstrings

  • Single-line comment: # explain why, not what.
  • Docstrings describe modules, classes, and functions. Example:
def fetch_user(user_id: str) -> dict:
"""Retrieve a user profile from the API."""
...

Common syntax gotchas

GotchaFix
Trailing whitespace before newlineTurn on "trim trailing whitespace on save" in your IDE.
Mixing tabs + spacesConfigure .editorconfig or IDE settings to convert tabs to spaces.
Misaligned multi-line stringsUse parentheses or textwrap.dedent() to keep indentation clean.

Style automation

  • Use Black for opinionated formatting.
  • Use Ruff or Flake8 to catch indentation and style issues.
  • Add a simple .editorconfig:
root = true

[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

Next up in your learning path

Frequently Asked Questions

Can I use tabs instead of spaces?

Python allows tabs, but the community standard is 4 spaces. Mixing tabs and spaces triggers `TabError`. Configure your editor to convert tabs to spaces automatically.

What line length should I follow?

PEP 8 recommends 79 characters for code and 72 for docstrings. Many teams adopt 88 characters when using Black. Configure your formatter accordingly.

How do I format strings across lines?

Wrap expressions in parentheses or use implicit string concatenation inside parentheses instead of escaping newlines.