Tech-savvy saving: how to build a budget tracker with a few lines of code in Python

Part 1 — Functions and Classes

Dimitrios Koulialias PhD
The Pythoneers
5 min readMar 13, 2024

--

Photo by Towfiqu barbhuiya on Unsplash

Have you ever wondered where all the money in your account has gone towards the end of the month? Don’t worry, you are not alone! Especially in these unpredictable times, in which purchase power is constantly affected by inflation, for many people, accurate budgeting has become more crucial than ever. Managing your monthly budget has nowadays never been that easy, given the myriad of apps and programs in the technological landscape that not only can assist you in tracking your daily expenses, but also in uncovering potential saving opportunities you might have been unaware of. On the other hand, wouldn’t it be exciting to create a budget tracker by yourself and shed light on your finances at the same time?

In this two-part article, we will tackle exactly that in Python. To do so, this part provides you with an introduction to functions and classes before we address the implementation in the follow-up article. Due to the powerful mechanism of functions and classes, especially the object-oriented programming context of the latter, having an overview thereof is essential in order to build the budget tracker in the most efficient way with minimal effort.

Functions: definition and examples

Let us first start with the definition of a function. A function refers to a section of a code that performs a specific task. Functions are usually common when you need to break down a large part of the code into smaller, manageable blocks. This is particularly useful in order to make a program more readable and to increase its comprehensibility. Once defined, a function can be called several times within a program without having to state the same logic and/or computation over and over again.

Within Python, the syntax of a function consists of the following structure:

def function_name(param):
"""Optional docstring"""
# Function body - code block
# return statement - used for returning a value (optional)

where the statements have the following meaning:

  • def’: A keyword that is used to define a function.
  • function_name’: Refers to the name of the function.
  • param’: This is a placeholder for one or several values, that are provided as input parameters to the function.
  • ‘:’: The double point occuring just after the closing bracket indicates the beginning of the function’s body.
  • “ “ “Optional docstring” ” ”: This docstring within triple quotes is a comment that gives a detailed explanation of what the function does. The inclusion of such docstring is optional.
  • Function body: This is the part of the Python code section that performs a specific task.
  • return’: This keyword specifies one or more values that are returned when calling the function. The return statement is optional; when omitted, the function returns ‘None’ by default.

A standard example that is included in many textbooks can be given by creating a function to perform a mathematical operation, e.g., to calculate the square of a number as

def square(number):
"""This function calculates the square of a given number."""
square_number = number * number
return square_number

After defining this function, you can test it by providing any input for the ‘number’ variable

result = square(3)
print(result) # Output: 9

Apart from the ‘def’ keyword, one can further create so-called lambda functions, also known as anonymous functions. They are often used to execute simple, one-line commands without having the need to write out the full function syntax. An example of a lambda function is shown below for adding 10 to an arbitrary input number x

y = lambda x: x + 10
print(y(2)) #returns 12

Classes: syntax and main characteristics

Now let’s draw our attention to classes. As key drivers of object-oriented programming, classes can be used as a means to create objects with specific attributes and functionalities.

The general syntax of a class within Python is as follows:

class ClassName:
<statement1>
<statement2>
.
.
<statementN>

where the first letter of the class name is usually capitalized.

In most cases, it is quite common to include a constructor within the syntax that is a special kind of function termed as __init__, and that is automatically generated after instantiating, i.e., creating a new object. The constructor can contain a set of parameters that are used to initialize the object attributes.

To better understand the class syntax and the constructor, let’s have a look on the following example of MyClass, that takes two parameters var1 and var2 and assigns them as attributes to an object

class MyClass:
def __init__(self, var1, var2): #Definition of the constructor
self.var1 = var1
self.var2 = var2

Here, the term self refers to the instance of a class and allows you to access the attributes using the dot (.) notation. Using the above example, we can instantiate an object termed as obj by passing the variables var1=’Hello ’ and var2=’World!’ and access them as follows:

obj = MyClass('Hello ', 'World!')
obj.var1 #Returns 'Hello '
obj.var2 #Returns 'World!'
obj.var1 + obj.var2 #Returns 'Hello World'!

Apart from attributes, one can also define functions within a class, as we have encountered in the special case of the constructor. More generally, functions that are defined within a class syntax are called methods. To illustrate the behavior of a method, we will make use of a more concrete example of a class that represents an object in everyday life. Since our story has an emphasis on financial aspects, let’s consider the example of an Account class, of which we can instantiate an account object. The account contains the name of the owner and the (initial) balance with respect to any currency, that we can modify by depositing or withdrawing money. All this can be implemented based on the following syntax:

class Account:
def __init__(self, owner_name, balance):
self.owner_name = owner_name
self.balance = balance

def deposit(self, value):
self.balance += value

def withdrawal(self, value):
self.balance -= value

Given this, we instantiate our own account object termed as MyAccount with an arbitrary balance of 1000 $, from which we do several deposits and withdrawals:

MyAccount = Account('Dimitrios Koulialias', 1000)
MyAccount.balance #Returns 1000
MyAccount.withdrawal(350)
MyAccount.balance #Returns 650
MyAccount.deposit(50)
MyAccount.balance #Returns 700

In this part of the article, you have gained an overview of functions and classes in Python, along with the object-oriented programming paradigm of the latter. In the follow-up part, we will stick to this paradigm in order to create the budget tracker and to equip it with the necessary functionalities.

--

--

Dimitrios Koulialias PhD
The Pythoneers

Physicist | Data and Finance enthusiast | Lifelong learner| PhD from Swiss Federal Institute of Technology (ETH Zurich)