Python Syntax: Indentation, Statements and Your First Program - Python with AI tutorial chapter 3
Python

Python Syntax: Indentation, Statements and Your First Program

Python with AI Tutorial · Chapter 3 of 48

Python syntax is the set of rules that decides how a Python program is written: one statement per line, indentation to group code blocks, a colon to open a block and no semicolons or braces. Because the rules are few, you can read most Python at first sight. This chapter covers each rule with a short, runnable example.

Statements: one instruction per line

A statement is a single instruction. In Python each statement normally sits on its own line, and the line ending is what separates one statement from the next. There is no semicolon to remember.

company = "Acme Supplies"
year = 2026
print(company, "annual report", year)
Output:
Acme Supplies annual report 2026

You can put two statements on one line with a semicolon (a = 1; b = 2), but Python style guides discourage it and you will never need it.

Indentation defines code blocks

This is the rule that makes Python different from almost every other language. Where JavaScript or VBA use braces or End If, Python uses the indentation itself. Every line indented under a header belongs to that header, and the block ends when indentation returns to the previous level.

invoice_total = 8200
if invoice_total > 5000:
    print("Large invoice")
    print("Manager approval required")
print("Processing finished")
Output:
Large invoice
Manager approval required
Processing finished

Think of indentation as the structure you would show in Excel with nested brackets, except that Python forces you to lay it out visibly. That is why programs written by different Python developers look so similar: the language itself enforces a tidy layout, and a reader can follow the logic without hunting for a closing brace.

The two indented print lines run only when the condition is true. The last line is not indented, so it runs every time. Change invoice_total to 800 and only Processing finished appears.

Common mistake: Python does not care whether you use 2, 3 or 4 spaces, but every line in the same block must use the same amount. The standard is 4 spaces, and VS Code inserts them when you press Tab. Never mix tabs and spaces in one file; that raises TabError.

The colon opens a block

Every statement that introduces a block ends with a colon: if, else, for, while, def, class, with, try. Forgetting the colon is the most common SyntaxError for beginners.

regions = ["North", "South", "West"]
for region in regions:
    print("Sales report:", region)
Output:
Sales report: North
Sales report: South
Sales report: West

Nested blocks

Blocks can live inside blocks. Each level simply indents four more spaces. Reading the indentation tells you exactly which lines belong to which condition.

orders = [1200, 450, 9800]
for amount in orders:
    if amount >= 1000:
        print(amount, "- priority")
    else:
        print(amount, "- standard")
Output:
1200 - priority
450 - standard
9800 - priority

Case sensitivity and keywords

Python is case-sensitive: Revenue, revenue and REVENUE are three different names. Around 35 words are reserved keywords and cannot be used as names. You do not need to memorise them; VS Code colours them for you and Python can list them.

import keyword
print(len(keyword.kwlist))
print(keyword.kwlist[:8])
Output:
35
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await']

Built-in function names such as print, len and sum are not keywords, so Python lets you overwrite them by accident. If you ever write sum = 500, the real sum() function disappears until the program restarts. Choose descriptive names such as sum_total instead. The table below collects the symbols you will use in every script.

Symbol Meaning in Python syntax Example
: Opens an indented block if x > 5:
4 spaces Marks a line as inside the block print(x)
# Starts a comment (ignored by Python) # monthly total
= Assigns a value to a name tax = 0.18
== Compares two values if tax == 0.18:
\ Continues a statement on the next line total = a + \

Long lines and line continuation

A statement usually ends at the line break, but anything inside brackets can span several lines, which keeps long lists or function calls readable. You can also end a line with a backslash, though brackets are the cleaner choice.

quarterly_sales = [
    45000,
    52000,
    48500,
    61000,
]
total = (quarterly_sales[0] + quarterly_sales[1]
         + quarterly_sales[2] + quarterly_sales[3])
print("Annual total:", total)
Output:
Annual total: 206500

Your first complete program

Put the rules together. This script calculates commission for a small sales team: a statement per line, a for block, an if/else block nested inside it, and consistent 4-space indentation.

team = {"Priya": 42000, "Daniel": 27500, "Chen": 51000}
rate_high = 0.10
rate_low = 0.05

for name, sales in team.items():
    if sales >= 40000:
        commission = sales * rate_high
    else:
        commission = sales * rate_low
    print(name, "earns", commission)
Output:
Priya earns 4200.0
Daniel earns 1375.0
Chen earns 5100.0

Notice commission is assigned inside the if/else but printed after it, at the for level. Indentation, not position on the page, decides when each line runs.

Try it with AI

Paste a deliberately broken version and let the assistant explain the error messages, which trains you to read them yourself.

This Python code has three syntax mistakes. For each one, quote the exact error message Python 3.12 would show, explain why it happens, and then give the corrected code:

team = {"Priya": 42000, "Daniel": 27500}
for name, sales in team.items()
    if sales >= 40000:
    print(name, "high")
    else:
        Print(name, "low")
Try it with AI

Ask for a comparison with the language you already know so indentation stops feeling strange.

I know Excel VBA (If ... End If, For ... Next). Rewrite this VBA in Python and then explain, in a short table, how Python indentation replaces each VBA End statement:

For Each amt In Array(1200, 450, 9800)
    If amt >= 1000 Then
        Debug.Print amt & " - priority"
    Else
        Debug.Print amt & " - standard"
    End If
Next amt

Common mistakes

  • Forgetting the colon after if, for or def: SyntaxError: expected ':'.
  • Indenting a line that should not be indented: IndentationError: unexpected indent.
  • Not indenting the line after a colon: IndentationError: expected an indented block.
  • Mixing tabs and spaces when pasting code from a website. Select all and use VS Code's Convert Indentation to Spaces.
  • Using = when you mean == in a condition. Python 3.12 helpfully says invalid syntax. Maybe you meant '==' or ':='?

Exercise

Write a program that loops over the expense amounts [250, 1800, 640, 3200] and prints Needs receipt for any amount of 500 or more and No receipt needed for the rest. After the loop, print Audit complete once.

Show answer
expenses = [250, 1800, 640, 3200]
for amount in expenses:
    if amount >= 500:
        print(amount, "Needs receipt")
    else:
        print(amount, "No receipt needed")
print("Audit complete")
Output:
250 No receipt needed
1800 Needs receipt
640 Needs receipt
3200 Needs receipt
Audit complete

Related chapters

FAQ

How many spaces should I use for Python indentation?

Four spaces per level is the official recommendation (PEP 8) and the VS Code default. Any consistent number works, but four is what every other Python programmer expects to see.

Does Python need semicolons at the end of lines?

No. A line break ends a statement. Semicolons are allowed only to separate two statements on one line, and style guides advise against that.

Why does my code give IndentationError after copying from a website?

The page probably mixed tabs and spaces or lost leading spaces. Retype the indentation, or in VS Code select all, open the Command Palette and run Convert Indentation to Spaces.

Working with spreadsheets too? Ready-made Excel, Google Sheets and Power BI templates are at NextGenTemplates.com.

Chapter 3 of 48 · Python with AI: all 48 chapters

PK
Meet PK, the founder of NeotechNavigators.com! With over 15 years of experience in Data Visualization, Excel Automation, and dashboard creation. PK is a Microsoft Certified Professional who has a passion for all things in Excel. PK loves to explore new and innovative ways to use Excel and is always eager to share his knowledge with others. With an eye for detail and a commitment to excellence, PK has become a go-to expert in the world of Excel. Whether you're looking to create stunning visualizations or streamline your workflow with automation, PK has the skills and expertise to help you succeed. Join the many satisfied clients who have benefited from PK's services and see how he can take your data analysis skills to the next level!
https://neotechnavigators.com