1. Introduction#

Effective programming combines problem-solving skills, domain knowledge, and programming skills; these notebooks will target each of these different areas. The overall goal, though, is not necessarily to teach you Python but rather how you can solve problems and perform tasks with computer programs.
A program is a series of instructions to carry out a specific task. These tasks can run a large gamut of possibilities:
solving mathematical problems
processing images and text
playing video games
analyzing financial data
making decisions (which covers another range from answering simple yes/no questions to driving a car).
Learning to program is not a passive activity. You cannot simply just read documentation and these notebooks. Becoming an effective programmer takes targeted practice, and that practice takes time. These notebooks will present fundamental concepts, how Python implements those concepts, and then how you can solve real problems with those concepts. These notebooks contain a large amount of Python code. Not only should you run this code, but you should also make changes to the code and see what happens. Do not be afraid to make mistakes - try things! The computer does not care and will not make fun of you. You should complete the exercises at the end of each notebook. Yes, we provide many of the answers. However, you will learn more by attempting the exercises on your own. We have written these exercises to reinforce the concepts presented.
By the end of this notebook, you will:
recognize what kinds of problems Python can solve in a FinTech context
identify the common structural elements shared by all programs (input, processing, output, state)
understand why abstraction and encapsulation matter, even before you can write programs yourself
The next notebook presents an approach to solving problems with programming. The fundamental principle is to understand what needs to happen, translate that understanding into a clear sequence of steps, and plan the solution before writing code.
To start our journey to learn computer programming through Python, this notebook contains three separate programs to demonstrate some of the capabilities of computer programs and some fundamental concepts within computer science. As these are some of the first Python programs you might have seen, we provide detailed explanations. We do not expect that you will now be able to write equivalent programs.
1.1. Sample Program: Budget Category Totals#
One of the most common financial technology tasks is taking a collection of transactions and turning them into useful information. In this example, we will read a small budget file, determine which categories appear in the file, and then compute how much money was spent in each category.
Even for a small file, a computer can summarize the data much faster and more reliably than a person doing arithmetic by hand.
The data for this example is stored in data/student_budget.csv. The file uses comma-separated values (CSV), a common text format for storing tabular data.
A sample of the file looks like this:
date,description,category,amount
2026-01-02,Coffee,Food,4.50
2026-01-02,Bus pass,Transportation,18.00
2026-01-03,Groceries,Food,52.30
2026-01-04,Movie ticket,Entertainment,14.00
The first row is the header. It tells us what each column represents. The following code snippet opens the file, loops through the first five lines, and prints each of those lines.
1with open("data/student_budget.csv") as f:
2 for _ in range(5):
3 print(f.readline().strip())
date,description,category,amount
2026-01-02,Coffee,Food,4.50
2026-01-02,Bus pass,Transportation,18.00
2026-01-03,Groceries,Food,52.30
2026-01-04,Movie ticket,Entertainment,14.00
Now let’s write a program to process the whole file. We will use a built-in data structure called a dictionary. A dictionary stores information in key-value pairs. In this case:
the key will be a category such as
FoodorTransportationthe value will be the running total for that category
This example uses several Python features we will study later. For now, focus on the big idea: the program reads transactions one at a time and keeps running totals by category. We are also showing the completed program now. In the next notebook, we will step backward and look at how we could design the program before we write code.
1category_totals = {}
2
3with open("data/student_budget.csv") as f:
4 header = f.readline()
5 for line in f:
6 date, description, category, amount = line.strip().split(",")
7 amount = float(amount)
8
9 if category not in category_totals:
10 category_totals[category] = 0
11
12 category_totals[category] += amount
13
14print(category_totals)
{'Food': 69.55, 'Transportation': 41.4, 'Entertainment': 23.990000000000002, 'Education': 86.47999999999999, 'Utilities': 64.2}
While you may be new to programming, hopefully you can see the main idea in the previous code block.
A few general notes:
The program opens the file and reads it one line at a time.
split(",")breaks each line into four pieces of data.float(amount)converts the text for the amount into a number so we can do arithmetic with it.The
ifstatement checks whether the category has appeared before.The dictionary
category_totalsgrows dynamically as the program discovers new categories in the file.The final
print()shows the totals that the program computed.
1categories = list(category_totals.keys())
2print(categories)
['Food', 'Transportation', 'Entertainment', 'Education', 'Utilities']
The variable categories is a list. A list stores multiple items in order. Here, the list contains the category names discovered in the file.
The following code block prints the number of entries in the list categories followed
by the entry in the second position. In Python, as in many languages influenced by C,
positions in a list start at 0 rather than 1. One way to think about this is that
an index describes an offset from the beginning of the list: index 0 means
“the first item,” index 1 means “one item after the first,” and so on.
This style of numbering is called zero-based numbering.
Try changing [1] to [0] or [2]. What happens if [1] is removed?
1print(len(categories))
2print(categories[1])
5
Transportation
This next code block loops over all of the categories and prints the totals in a more readable format. (We’ll present this string formatting several notebooks from now.)
1overall_total = 0
2
3for category in categories:
4 amount = category_totals[category]
5 overall_total += amount
6 print(f"{category:>15}: ${amount:,.2f}")
7
8print(f"{'Total':>15}: ${overall_total:,.2f}")
Food: $69.55
Transportation: $41.40
Entertainment: $23.99
Education: $86.48
Utilities: $64.20
Total: $285.62
This example shows one of the strengths of computing. Rather than manually adding up values for each category, the program reads the file, discovers the categories that appear, and computes the totals consistently. As we continue through these notebooks, we will build the tools needed to write these kinds of financial data processing programs more systematically.
1.2. Sample Program: Reaching Savings Goals#
Another common financial question is: how long will it take to reach a savings target? The following example models monthly deposits into an account that earns interest. A computer is useful here because it can apply the same financial rules month after month without getting tired or making arithmetic mistakes.
1target = 10_000
2monthly_deposit = 250
3annual_interest_rate = 0.04
4monthly_interest_rate = annual_interest_rate / 12
5
6balance = 0
7months = 0
8
9while balance < target:
10 balance = balance * (1 + monthly_interest_rate)
11 balance = balance + monthly_deposit
12 months += 1
13
14print("Months:", months)
15print(f"Balance: ${balance:.2f}")
Months: 38
Balance: $10109.97
In the previous code block, each repetition of the while loop represents one month. The program first adds a month’s worth of interest and then adds the new deposit. This kind of repeated calculation is one of the strengths of computing.
1years = months // 12
2remaining_months = months % 12
3
4print(f"It will take {years} years and {remaining_months} months.")
It will take 3 years and 2 months.
Now suppose we want to compare several different monthly deposit amounts. Rather than solving each case by hand, the computer can evaluate several savings plans quickly and consistently.
1monthly_deposits = [100, 150, 200, 250, 300]
2results = []
3
4for deposit in monthly_deposits:
5 balance = 0
6 months = 0
7 while balance < target:
8 balance = balance * (1 + monthly_interest_rate)
9 balance = balance + deposit
10 months += 1
11 results.append((deposit, months, balance))
12
13print(results)
[(100, 87, 10073.494059057506), (150, 61, 10127.996216486557), (200, 47, 10158.059998556102), (250, 38, 10109.96591933108), (300, 32, 10112.940460534512)]
The variable results is a list. Each entry stores three pieces of information:
the monthly deposit amount
the number of months needed to reach the goal
the final balance when the loop stops
In this next code block, we’ll pull out the separate pieces of information into different variables and show that information to the user. We’ve used some additional logic and formatting to make the output cleaner than just simply printing a list of values.
1for deposit, months_needed, final_balance in results:
2 years = months_needed // 12
3 remaining_months = months_needed % 12
4 print(
5 f"${deposit:>3} per month -> "
6 f"{years} year{'s' if years != 1 else ''}, "
7 f"{remaining_months} month{'s' if remaining_months != 1 else ''}, "
8 f"ending balance ${final_balance:,.2f}"
9 )
$100 per month -> 7 years, 3 months, ending balance $10,073.49
$150 per month -> 5 years, 1 month, ending balance $10,128.00
$200 per month -> 3 years, 11 months, ending balance $10,158.06
$250 per month -> 3 years, 2 months, ending balance $10,109.97
$300 per month -> 2 years, 8 months, ending balance $10,112.94
1.3. Sample Program: Traveling Salesperson and Solvability#
Fundamentally, computer science is concerned with asking if a particular problem can be solved and, if it is solvable, how expensive is a specific solution.
One of the most well-studied problems in computer science is the traveling salesperson problem. Suppose a salesperson has to visit \(n\) cities and return to that starting point. What is the shortest route that visits each city exactly once?
The brute-force method would be to try all possible permutations of the city routes. With three cities, the following possibilities exist:
City 1, City 2, City 3
City 1, City 3, City 2
City 2, City 1, City 3
City 2, City 3, City 1
City 3, City 1, City 2
City 3, City 2, City 1
How long would it take to search all the possibilities to find the optimal answer?
\(n!\) possible permutations exist.
Assuming we can search one billion possibilities in a second, how much time is required to solve the problem for 20 cities? 100 cities?
1import math
2
3num_sec_in_day = 24 * 60 * 60
4num_tries_per_second = 1_000_000_000
5num_cities = 20
6num_route_permutations = math.factorial(num_cities)
7num_days = num_route_permutations // num_tries_per_second // num_sec_in_day
8print(f"{num_days:,}")
28,158
Try running the above code block for different values for the number of cities. If you use a small value, the program prints zero as the code uses integral division // which discards the remainder (e.g., 5 // 2 has the result of 2, not 2.5). For small values, take out // num_sec_in_day to see the number of seconds or alter the assumption of one billion tries per second. How could you convert the result to the number of years? Try making these code changes in the above cell and re-running the cell. Part of being a computer scientist is to explore different possibilities.
You can also step through the code to see what occurs on each program step.
The traveling salesperson problem has direct applicability to real-life:
Paths robots need to take for manufacturing (e.g., welding a car, soldering a circuit board)
Delivery schedules for companies such as Amazon, FedEx, and UPS.
1.4. What is a Program?#
As mentioned at the start of this notebook, a program is a series of instructions to carry out a specific task. As you ran through these different examples, you may have noticed a few commonalities.
Each of these programs had some sort of input. In these examples, the inputs came from a file of transactions, a set of savings assumptions, and the number of cities.
Each of the programs had some sort of output (result).
All of the programs had some form of sequence of commands with assignments, mathematical operations, or other statements.
Each program used variables to hold information containing the current state of the program.
Each program used existing libraries and functions to produce the desired functionality. One aspect of modern programming is not only learning the syntax (the rules) of a programming language, but learning how to find and use existing libraries.
Additionally, as these notebooks will demonstrate, programs typically contain some form of conditional expression that determines if different blocks of code should execute. Finally, the last fundamental commonality is that programs will regularly have some form of repetition where an action (or sequence of actions) will repeat.
1.5. Abstraction and Encapsulation#
One of the keys to successful programming is to apply fundamental programming principles. In this notebook, we have relied heavily upon two, abstraction and encapsulation, frequently appearing together. Abstraction seeks to distill a concept into its fundamental parts, while encapsulation bundles those parts and hides the implementation’s necessary and sometimes complex details. With abstraction, we focus on the outside view of an object or function, while encapsulation hides the exact details and steps to perform a specific task. For example, the budget-total program abstracted the problem into a few core pieces: opening a file, reading lines, determining categories, and updating totals. The savings-goal example abstracts a different financial process into a target amount, a deposit amount, an interest rate, and repeated monthly updates to the balance. Likewise, the traveling salesperson example hides the details of factorial computation behind Python’s math.factorial() function.
We take advantage of abstraction, encapsulation, and other programming principles when we use existing classes, modules, and functions. As a result, we can solve real-life problems by focusing on the essential parts without understanding the precise implementation details. Throughout these notebooks, we will apply programming principles to model real-life systems, problems, and tasks.
1.6. Python Documentation#
Python offers substantial documentation - both from within the interpreter with the help() function and online.
The homepage for the Python documentation is at https://docs.python.org/3/
Visit that site and see what is available.
1.7. Suggested LLM Prompts#
Explain computer programming to me as if I were a college student using finance topics.
Explain the difference between abstraction and encapsulation in Python programming. Provide code examples using finance topics.
Provide 5 examples of intractable problems in computer science. Explain how each relates to financial technology.
1.8. Review Questions#
At the end of many of these notebooks, we will have a series of questions to reflect and review upon the material. Some questions are meant for you to reflect and do not necessarily have correct answers, while others are meant to directly test your recollection and understanding of the material.
How do problem-solving skills, domain knowledge, and programming skills combine together for effective programming? What does each bring?
Besides your laptop and smartphone, where is software present in your daily life? Where is software not present?
In one sentence each, state what question each of the sample programs answers. Identify the commonalities among those three programs.
Explain the importance of abstraction and encapsulation in programming, as discussed in the text. Provide examples to illustrate how these principles are applied in real-life programming scenarios.
Which is a key aspect of programming?
- Accurate syntax
- Memorization of language features and library functions
- Understanding what needs to occur
- Copying code without understanding it
What is the primary purpose of abstraction in programming?
- To bundle complex details within an object.
- To reveal the precise implementation details of a concept.
- To simplify a concept by distilling it to its fundamental parts.
- To focus solely on the internal workings of a function.
What is the primary definition of a program?
- A collection of random instructions.
- A set of commands that can only be executed once.
- A series of instructions designed to automate tasks.
- A list of variables and their values.