Skip to content
C Codeloom
Python

Python Syntax and Indentation Explained

Understand Python's syntax rules, the role of indentation, statements, comments, and the most common syntax errors that trip up new developers.

·7 min read · By Yash Kesharwani
Beginner 9 min read

What you'll learn

  • The basic rules that define valid Python code
  • Why Python uses indentation instead of braces, and how to use it correctly
  • How to write statements, comments, and multi-line code
  • The three most common syntax errors and how to fix them

Prerequisites

Every programming language has rules about how source code must be written. These rules are called the language’s syntax. Python’s syntax is unusually small and consistent, which is one reason the language is so approachable. This post covers everything you need to write valid Python from day one.

Statements: one instruction per line

A statement is a single instruction for Python to execute. The simplest convention is one statement per line:

print("Hello, world!")
print("Welcome to Python.")
print("Let's begin.")

Run that program and you get three lines of output. Each line is read, executed, and forgotten before the next one begins.

You can place multiple statements on a single line by separating them with semicolons, but this is strongly discouraged in practice. It is included here only so you recognise it if you see it in older code:

print("a"); print("b"); print("c")   # works, but please don't

Stick to one statement per line. Python’s design assumes it, and your editor’s tooling assumes it too.

Indentation: Python’s defining feature

Most programming languages use curly braces { } to group code into blocks. Python uses indentation — the empty space at the start of a line — for the same purpose. This is the single biggest difference between Python and almost every other mainstream language.

Compare an if statement in JavaScript and Python:

// JavaScript
if (age >= 18) {
    console.log("Adult");
    console.log("You can vote.");
}
# Python
if age >= 18:
    print("Adult")
    print("You can vote.")

In Python, the colon : opens a new block, and the indented lines underneath belong to that block. There are no braces — the indentation is the structure.

The indentation rules

  1. Use four spaces per level. This is the universal convention, codified in Python’s official style guide (PEP 8).
  2. Be consistent. Every line inside the same block must be indented by the same amount. Mixing four spaces and two spaces in the same block is a syntax error.
  3. Do not mix tabs and spaces. Pick one — modern Python tooling defaults to spaces — and stay with it. VS Code handles this for you automatically.

If the rules are followed, your code is correct. If they are not, Python refuses to run the program.

# Correct
if True:
    print("Inside the block")
    print("Still inside")
print("Outside the block")
# Incorrect — inconsistent indentation
if True:
    print("Inside")
  print("Also inside?")   # IndentationError

Why indentation?

Newcomers sometimes find this design frustrating. Experienced developers almost universally come to appreciate it. The reasoning is straightforward: in languages with braces, developers indent code anyway, for humans to read. Python simply makes that indentation meaningful to the computer too. The result is that all Python code looks similar, regardless of who wrote it. There are no debates about brace placement.

Try it yourself. Create a file called indent.py and copy the “Correct” example above into it. Run it. Then break the indentation deliberately — add an extra space, or remove one — and run it again. Read the error message carefully. Learning to read Python’s error messages is a skill in itself.

Comments: notes for humans

A comment is text the Python interpreter ignores. Comments exist solely for the humans reading the code — usually your future self.

Single-line comments start with #:

# Calculate the total price including 18% sales tax
price = 100
total = price * 1.18
print(total)

There is no separate multi-line comment syntax in Python. For longer notes, use multiple single-line comments:

# This function computes compound interest.
# It takes the principal, rate, and number of years
# and returns the final amount.

Triple-quoted strings (""" ... """) are sometimes used as multi-line comments. Strictly speaking they are strings that Python evaluates and then discards, but in practice they read fine for documentation:

"""
A short explanation of what this script does,
written across several lines.
"""

Good comments explain why a piece of code exists, not what it does. The code itself shows what it does. The reason it does it is often invisible.

Case sensitivity and naming

Python is case-sensitive. The names Name, name, and NAME refer to three completely different things:

name = "Alice"
Name = "Bob"
print(name)   # Alice
print(Name)   # Bob

This catches almost every beginner at least once. If your code “should work” but doesn’t, double-check capitalisation first.

The community convention for variable names is snake_case — lowercase words joined by underscores:

user_name = "Alice"
total_price = 199.99
is_logged_in = True

Classes use PascalCase (we’ll meet classes later in the series), and constants use UPPER_SNAKE_CASE.

Splitting long lines

Occasionally a single statement is too long to fit comfortably on one line. Python offers two clean ways to split it.

Implicit continuation — anything inside ( ), [ ], or { } can wrap freely:

total = (
    item_price
    + shipping_cost
    + sales_tax
    - discount
)

Explicit continuation with a backslash works but is considered less readable:

total = item_price + shipping_cost \
      + sales_tax - discount

Prefer the implicit form. Almost all real Python code uses it.

The three most common syntax errors

Nearly every beginner hits the same three errors in their first week. Recognising them on sight will save hours.

1. IndentationError: unexpected indent

A line is indented when it shouldn’t be, or indented more than the surrounding code.

print("Hello")
   print("World")   # IndentationError

Fix: remove the leading spaces. Only indent when entering a block (after a :).

2. SyntaxError: expected ':'

You started a block — if, for, while, def, class — but forgot the colon at the end of the line.

if age >= 18
    print("Adult")   # SyntaxError

Fix: add the colon.

if age >= 18:
    print("Adult")

3. SyntaxError: EOL while scanning string literal

You opened a quote and never closed it. EOL stands for “end of line.”

print("Hello, world)   # SyntaxError — missing closing quote

Fix: add the missing quote. The position of the error in the traceback usually points to the offending line.

Try it yourself. Open a file, reproduce each of the three errors deliberately, and read the error messages Python prints. Python’s tracebacks are precise — they almost always tell you the file, the line number, and the type of problem. Learning to trust them will speed up your development dramatically.

A complete example

The program below demonstrates everything covered in this post: statements, indentation, comments, and naming.

# Greet a user based on the time of day.
hour = 14

if hour < 12:
    greeting = "Good morning"
elif hour < 18:
    greeting = "Good afternoon"
else:
    greeting = "Good evening"

user_name = "Yash"
print(greeting + ", " + user_name + "!")

Save it as greet.py, run it with python greet.py (or python3 greet.py), and you should see:

Good afternoon, Yash!

Change the value of hour to test the other two branches.

Recap

You now know:

  • Python uses one statement per line and indentation to define blocks
  • The standard indent is four spaces, and it must be consistent within a block
  • Comments start with # and are ignored by the interpreter
  • Python is case-sensitive and uses snake_case for variables
  • The three most common syntax errors and how to fix them on sight

That is genuinely most of Python’s syntax. Everything else in the language is just specific kinds of statements and expressions that follow these rules.

Next steps

In the next post we look at variables and naming in detail: how to store values, how Python decides their type, and the conventions that distinguish professional code from amateur code.

→ Next: Variables and Naming in Python (coming soon)

Questions or corrections? Email codeloomdevv@gmail.com.