Python for Finance: Your First Steps

Python is a programming language, a way of giving your computer clear instructions in simple English-like words. Finance and accounts teams use it to do the boring, repeated work that eats their day: adding GST to hundreds of invoices, checking expenses against a budget, or joining ten Excel files into one. In this lesson you will write your very first Python code, step by step, with small finance examples you already know from Excel.

What you will learn

  • Why finance people use Python, and where it helps more than Excel
  • How to start with Google Colab (nothing to install) or Anaconda (on your own computer)
  • How a Jupyter notebook works: cells, running code and reading the output
  • The building blocks: variables, numbers, text (strings), lists and dictionaries
  • How to make decisions with if, repeat work with for loops and save your logic in functions
  • Real examples: GST on an invoice, an EMI calculator and a budget versus actual check

Why finance people use Python

Think of Python as a helper that sits next to Excel, not a replacement for it.

Python helps most in these situations:

  • The same steps every month. If you clean the same bank statement or sales file every month, you can write the steps once in Python and run them again in seconds.
  • Many files. Joining 12 monthly files or 50 branch files by hand is slow and easy to get wrong. Python can read a whole folder in one go.
  • Big data. An Excel worksheet stops at 1,048,576 rows. Python can work with files bigger than that.
  • A clear record of the steps. Your code is a written list of exactly what was done to the data. Your manager or auditor can read it and run it again.

Remember: You do not need to be good at maths or computers to start. If you can write an Excel formula, you can write simple Python.

Two ways to start: Google Colab or Anaconda

You need a place to type and run Python. There are two easy choices. Pick one, you can always try the other later.

Option 1: Google Colab (nothing to install)

Google Colab runs Python inside your web browser. It is free with a Google account and is the fastest way to start, even on an office laptop where you cannot install software.

  1. Open your browser and go to colab.research.google.com.
  2. Sign in with your Google account.
  3. Select File > New notebook in Drive.
  4. A new notebook opens with one empty box, called a cell. You will type your code here.

Note: Colab runs on Google’s computers, not yours. Do not upload real client data, salary data or anything confidential to it without your company’s permission. Use practice data like the examples in this lesson.

Option 2: Anaconda (on your own computer)

Anaconda is a free package that installs Python plus the most used data tools (pandas, Jupyter and many more) in one go. Use it if you want to work with files on your own computer.

  1. Go to anaconda.com/download and download the installer for Windows or Mac.
  2. Run the installer and accept the default options.
  3. Open Anaconda Navigator from your Start menu (Windows) or Applications folder (Mac).
  4. Launch Jupyter Notebook. It opens in your browser and shows the folders on your computer.
  5. Go to the folder where you want to save your work, then select New > Notebook. If Jupyter asks you to pick a kernel (the engine that runs your code), choose Python 3 (ipykernel).

This chart shows the two paths. Read it from top to bottom. At the diamond, answer the question and follow the arrow.

Choose where to run your first Python codeYou want to try PythonCan you installsoftware on thiscomputer?NoUse Google Colab inyour browserYesDownload and installAnacondaOpen Anaconda NavigatorLaunch Jupyter NotebookSelect New, then NotebookEmpty notebook ready forcodeStart / EndDecisionStep
Choose where to run your first Python code

How to read a flowchart

We use flowcharts in our lessons to show a process as a picture. Each shape has a meaning:

SymbolNameWhat it means
Rounded boxStart or EndWhere the process begins or finishes
RectangleStep (process)Something you do, like “Run the cell”
DiamondDecisionA yes or no question. Yes goes down, No goes to the side
Slanted boxInput or OutputData coming in or results going out
Box with a wavy bottomDocumentA report, form or printed result
CylinderSystem or DataA database, an ERP or a saved file store

How a notebook works

A notebook is a page made of cells. You type code in a cell, run it, and the answer (the output) appears just below that cell. This is a lot like typing a formula in Excel and seeing the result in the cell.

  1. Click inside a cell.
  2. Type print("Hello, Sharma Traders").
  3. Press Shift + Enter to run the cell. In Colab you can also select the round play button on the left of the cell.

You should see this output below the cell:

Hello, Sharma Traders

print() is a function, a ready-made command that does one job. This one shows whatever you put inside the brackets. The text is inside double quotes so Python knows it is text, not a command.

Shortcut: Shift + Enter runs the cell and moves to the next one. Ctrl + Enter runs the cell and stays on it.

Every time you work in a notebook you follow the same loop. The chart below shows it. If the answer to the question is No, fix the code and run it again.

How you work in a notebook cellOpen your notebookType code in a cellPress Shift + Enter to runitDid it run withoutan error?NoRead the last errorline, fix, run againYesOutput appears below thecellAdd a new cell for the nextstepSave the notebookStart / EndStepDecisionInput / Output
How you work in a notebook cell

Tip: When you see an error, read the last line first. It usually says what went wrong in plain words, like NameError: name 'Total' is not defined.

Variables and numbers: GST on an invoice

A variable is a name that holds a value, like a labelled box. In Excel you would put 25000 in cell B2 and refer to B2. In Python you give the value a name instead.

Let us work out 18% GST on an invoice of Rs 25,000.

amount = 25000
gst_rate = 18
gst = amount * gst_rate / 100
total = amount + gst
print("GST:", gst)
print("Total:", total)

Output:

GST: 4500.0
Total: 29500.0

Line by line:

  1. amount = 25000 puts 25000 in a box named amount. The = sign here means “store this”, not “is equal to”.
  2. gst_rate = 18 stores the rate.
  3. gst = amount * gst_rate / 100 multiplies and divides, just like an Excel formula, and stores the answer in gst.
  4. total = amount + gst adds the two.
  5. print("GST:", gst) shows a label and the value. A comma inside print() puts a space between them.

You may wonder why the answer is 4500.0 and not 4500. In Python, dividing with / always gives a decimal number. Python has two kinds of numbers: whole numbers (called int, short for integer) and decimal numbers (called float).

Here are the maths signs you will use most:

PythonMeaningExampleResult
+Add25000 + 450029500
-Subtract29500 - 450025000
*Multiply25000 * 18450000
/Divide450000 / 1004500.0
**Power2 ** 38
//Divide, keep the whole part7 // 23
%Remainder7 % 21

Common mistake: Do not type commas inside numbers. x = 1,00,000 does not give one lakh. Python reads it as three separate numbers and gives (1, 0, 0). Write 100000, or use underscores to make it readable: 1_00_000 gives 100000.

Text (strings): customer names and invoice lines

Text in Python is called a string. A string always goes inside quotes, single '...' or double "...". Use straight quotes. Curly quotes copied from Word or WhatsApp give an error.

customer = "Sharma Traders"
invoice_no = "INV-1042"
total = 29500
print(customer.upper())
print(f"Invoice {invoice_no} for {customer}: Rs {total:,.2f}")
print(type(total), type(customer), type(18.5))

Output:

SHARMA TRADERS
Invoice INV-1042 for Sharma Traders: Rs 29,500.00
<class 'int'> <class 'str'> <class 'float'>

What is happening here:

  • customer.upper() changes the text to capital letters, like Excel’s =UPPER(A2).
  • The line that starts with f" is an f-string. Anything inside curly brackets { } is replaced with the value of that variable. It works like joining text in Excel with &, but it is much easier to read.
  • {total:,.2f} means “show total with a comma separator and 2 decimal places”.
  • type() tells you what kind of value something is: int (whole number), str (string) or float (decimal).

Note: The comma format uses the international style. Rs 12,50,000 will print as 1,250,000.00. The value is correct, only the grouping of the digits is different from the Indian lakh style.

Lists: a month of expense bills

A list holds many values in one variable, in order. Think of it as one column of numbers in Excel. You write a list inside square brackets, with commas between the items.

expenses = [1200, 450, 3000, 800, 2550]
print("Number of bills:", len(expenses))
print("Total spent:", sum(expenses))
print("Biggest bill:", max(expenses))
print("Average bill:", sum(expenses) / len(expenses))
print("First bill:", expenses[0])
expenses.append(999)
print(expenses)

Output:

Number of bills: 5
Total spent: 8000
Biggest bill: 3000
Average bill: 1600.0
First bill: 1200
[1200, 450, 3000, 800, 2550, 999]
  • len() counts the items, like =COUNT() in Excel.
  • sum() and max() work like =SUM() and =MAX().
  • expenses[0] picks the first item. Python starts counting from 0, so the second item is expenses[1].
  • expenses.append(999) adds a new bill to the end of the list.

Dictionaries: a budget with labels

A list has no labels. Very often in finance we want a label with every number: Rent 40,000, Electricity 6,000. For that, Python has a dictionary. Each item is a pair of a key (the label) and a value (the number), written as key: value inside curly brackets.

budget = {"Rent": 40000, "Electricity": 6000, "Travel": 15000}
print(budget["Rent"])
budget["Internet"] = 2000
print(budget)
print("Total budget:", sum(budget.values()))

Output:

40000
{'Rent': 40000, 'Electricity': 6000, 'Travel': 15000, 'Internet': 2000}
Total budget: 63000
  • budget["Rent"] looks up the value for the key Rent. It is a tiny version of VLOOKUP.
  • budget["Internet"] = 2000 adds a new pair.
  • budget.values() gives just the numbers, so sum() can add them.

Remember: Keys are case sensitive. budget["rent"] with a small r gives a KeyError, because the key is "Rent".

Making decisions with if

In Excel you use =IF() to choose between two answers. Python has if, elif (short for “else if”) and else.

Say your company has a simple approval rule: above Rs 50,000 a manager approves, above Rs 10,000 a team lead approves, and anything smaller is approved automatically.

amount = 72000
if amount > 50000:
    print("Needs manager approval")
elif amount > 10000:
    print("Needs team lead approval")
else:
    print("Auto approved")

Output:

Needs manager approval

Two details matter here:

  1. Every if, elif and else line ends with a colon :.
  2. The line under it is pushed in by 4 spaces. This is called indentation, and it tells Python “this line belongs to the if above”. Jupyter and Colab add the spaces for you when you press Enter after a colon.

Python checks the conditions from top to bottom and stops at the first one that is true. The chart shows the same rule as a picture.

Invoice approval rule with if, elif and elseInvoice amount enteredIs the amount 50,000or less?NoNeeds managerapprovalYesIs the amount 10,000or less?NoNeeds team leadapprovalYesAuto approve the invoiceApproval route decidedStart / EndDecisionStep
Invoice approval rule with if, elif and else

In this chart a No answer goes to the side and stops the checking. Only when the answer is Yes does Python move down to the next question. The chart asks the questions the other way round from the code, but the result is the same.

To compare values, use these signs. Note that “is equal to” is two equals signs.

PythonMeaningExcel
==Is equal to=
!=Is not equal to<>
> and <Greater than, less than> and <
>= and <=Greater or equal, less or equal>= and <=

Repeating work with for loops

A for loop repeats the same steps for every item in a list. It is like writing a formula in row 2 and dragging it down to the last row.

invoices = [10000, 25000, 4800]
for amount in invoices:
    gst = amount * 18 / 100
    print(amount, "GST:", gst, "Total:", amount + gst)
print("Done")

Output:

10000 GST: 1800.0 Total: 11800.0
25000 GST: 4500.0 Total: 29500.0
4800 GST: 864.0 Total: 5664.0
Done

Read the first line as plain English: “for each amount in the invoices list, do the indented steps”. The first time round, amount is 10000, then 25000, then 4800. The line print("Done") is not indented, so it runs only once, after the loop has finished.

Functions: write the logic once, use it everywhere

You have already used ready-made functions like print(), sum() and len(). You can also make your own with the word def (short for define). A function takes some inputs, does its work and gives back an answer with return.

def add_gst(amount, rate=18):
    return amount + amount * rate / 100

print(add_gst(10000))
print(add_gst(10000, 5))

Output:

11800.0
10500.0

rate=18 is a default value. If you do not give a rate, Python uses 18. For a 5% item you pass the rate yourself.

An EMI calculator

Now something every finance person uses: the EMI (equated monthly instalment) on a loan. The formula is:

EMI = P * r * (1 + r) ** n / ((1 + r) ** n - 1)

Here P is the loan amount, r is the monthly interest rate and n is the number of months. Let us find the EMI on a loan of Rs 5,00,000 at 9% a year for 5 years.

def emi(principal, annual_rate, years):
    r = annual_rate / 12 / 100
    n = years * 12
    return principal * r * (1 + r) ** n / ((1 + r) ** n - 1)

monthly = emi(500000, 9, 5)
print(f"EMI: Rs {monthly:,.2f}")
print(f"Total paid: Rs {monthly * 60:,.2f}")
print(f"Total interest: Rs {monthly * 60 - 500000:,.2f}")

Output:

EMI: Rs 10,379.18
Total paid: Rs 622,750.66
Total interest: Rs 122,750.66
  1. r = annual_rate / 12 / 100 turns 9% a year into a monthly rate (0.0075).
  2. n = years * 12 turns 5 years into 60 months.
  3. The return line is the EMI formula, using ** for “to the power of”.

You can check this in Excel: =PMT(9%/12,60,-500000) also gives 10,379.18. Getting the same answer from two tools is a good habit before you trust any new calculation.

Putting it together: budget versus actual

Now let us join everything: two dictionaries, a loop, an if and an f-string. We compare this month’s actual spend with the budget for each expense head.

budget = {"Rent": 40000, "Electricity": 6000, "Travel": 15000}
actual = {"Rent": 40000, "Electricity": 7450, "Travel": 12300}

for head in budget:
    diff = actual[head] - budget[head]
    if diff > 0:
        print(f"{head}: over budget by Rs {diff:,}")
    else:
        print(f"{head}: within budget")

Output:

Rent: within budget
Electricity: over budget by Rs 1,450
Travel: within budget

When you loop over a dictionary, you get its keys one by one: Rent, then Electricity, then Travel. For each key we look up both numbers, find the difference and decide what to print. The chart shows the same steps.

Budget versus actual check for each expense headBudget and actual figuresreadyTake the next expense headDifference = actual minusbudgetIs the difference 0or less?NoPrint over budget bythe differenceYesPrint within budgetAre all headschecked?NoGo back to the nextexpense headYesVariance list completeStart / EndInput / OutputStepDecision
Budget versus actual check for each expense head

Excel and Python side by side

What you wantIn ExcelIn Python
Store a valueType 25000 in B2amount = 25000
Calculate=B2*18%gst = amount * 18 / 100
Add a column=SUM(B2:B6)sum(expenses)
Capital letters=UPPER(A2)customer.upper()
Choose an answer=IF(B2>50000,"Manager","Auto")if amount > 50000:
Repeat for every rowDrag the formula downfor amount in invoices:
Look up a label=VLOOKUP("Rent",A2:B4,2,FALSE)budget["Rent"]
Loan EMI=PMT(9%/12,60,-500000)emi(500000, 9, 5)

Common mistakes

  • Missing colon or spaces. Forgetting the : after if, for or def, or forgetting to indent the next line. Python stops with an error like this:
IndentationError: expected an indented block after 'if' statement on line 2
  • Curly quotes. Code pasted from Word, email or WhatsApp often has curly quotes. Retype them as straight quotes ".
  • Using = when you mean ==. One equals sign stores a value. Two equals signs compare.
  • Wrong capital letters. Total and total are two different names. Using a name that was never created gives NameError: name 'Total' is not defined.
  • Running cells out of order. If cell 3 uses a variable made in cell 2, run cell 2 first. When things get confusing, use Runtime > Run all in Colab, or Kernel > Restart Kernel and Run All Cells in Jupyter Notebook, to run everything from the top.
  • Commas inside numbers. Write 100000 or 1_00_000, never 1,00,000.

Quick recap

  • Python is a helper next to Excel for repeated steps, many files and big data.
  • Start in Google Colab with nothing to install, or install Anaconda and use Jupyter Notebook.
  • Type code in a cell and press Shift + Enter to run it. The output appears below.
  • Variables hold values, strings hold text, lists hold many values and dictionaries hold labelled values.
  • if makes decisions, for repeats steps, and def saves your logic as a function you can use again.

Try it yourself

Open a new notebook in Colab or Jupyter and try these four small tasks. Run each one in its own cell.

  1. Store an invoice amount of Rs 48,000 and work out GST at 12%. Print the GST and the total with an f-string and 2 decimal places. You should get Rs 5,760.00 and Rs 53,760.00.
  2. Make a list of your last five household bills. Print the total, the biggest bill and the average.
  3. Use the emi() function to find the EMI on Rs 20,00,000 at 8.5% for 20 years. Then check your answer in Excel with =PMT(8.5%/12,240,-2000000).
  4. Add a new head "Internet": 2000 to the budget and "Internet": 2600 to the actual figures, and run the budget versus actual check again. Internet should now show as over budget by Rs 600.

Where to go next

Keep going

102 free lessons across 6 topics

All articles