Abano

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

Budget manager

Managing money can be a tedious task, which can be made


easier with a computer. There are various apps for tracking
what you spend, based on setting budgets for different
kinds of eHpenses. This project will create a simple budget
manager using Python dictionaries and classes.

What the program does Budget planner


This budget manager will allow users to keep track of their Rather than directly creating a program,
expenditure against an overall budget of 2500. To start, a budget is this project will create a set of
functions that can be called from the
allocated for different kinds of expenditure, such as groceries and Python shell. These functions can also
household bills. be imported and used in other
The expenses can then be compared against their allocated budget. programs.
A summary is displayed to get a quick overview of the finances.

Python3.7.0Shel

» add_budget(“Groceries“, 500)
2000.00
Allocates spend
> > > add_budge t ("Rent" , 900) against budget

1100.00
>>> spend(“Groceries“, 35)
Returns the
465 . 00 budget left

> > > spend {" G roce r i es" , 15)


450 . 00
»> print_summary()

Budget Budgeted Spent Remaining

G roce r i es 500. 00 50 . 00 450 . 00


Rent 900 . 00 0. 00 900. 00

To ta I 1400. 00 50 . 00 1350 . 00

The summary
gives
PYTHON
Budget manager 1 5«°/ 59

7 How to use Python dictionaries 3 How to raise exceptions for errors 7 How to format strings for output
fi How to create a Python class
Lines of code: 43
Difficulty level
ee

The llbrary developed in this project, with the addition of a user interface, can be used in a simple financial-planning application. Split

Function calls
The functions written in this program will allow Program design
you to allocate an amount of income to different In this project, functions are added
named
budgets. The functions will then track spending sequentially to create the budget library.
against these budgets to see the total amount spent Then, a summary of all the expenses is
compared to the amount that was budgeted. The printed. In the end, all the code is converted
diagram below shows an example of making a
series of function calls. into a Python class to make it more useful.
BUDGET
LIBRARY LIBRARY
USER

add_budget ("Groceries", 500) Add expenditure

2000 Add budget

Print sum ary


add_budget ("Rent", 900)

Convert the code to aclass

°°

spend ("Groceries", 15)


Setting up
To create this budget manager, you will need a new
Python file. You can then add some basic code to the file and
build on it later. The use of Python dictionaries will allow
you to save the amount budgeted and spent.

CREATE A NEW FILE


The first step is to create a new file that will
contain the code for this project. Open IDLE and select
New File from the File menu. Create a new folder on your
desktop called BudgetManager, and save this empty file
inside it. Name the file “budget.py”. BUDGET.PY
BUDGET
MANAGER

ET UP THE VAR ABLE


Now create some global variables that
Sets the variable
will track the amount of money available, the avai lable = 2500.00
amount you have budgeted, and the amount a val I able to
an example
spent. You will use Python dictionaries (see budgets = {} starting amount
box, below) for the budgets and expenditure
that will map from a name, such as “Groceries”, expend iture =
to an amount of money.
Type this code into the new file. {}
Curly brackets are used
to
create a dictionary —an empty
dictionary in this instance

ESDDCT ONAR
When deciding what Python data structure to use,
another, such as an amount of money. In the
think about how you would write the information to
table below, the first column contains the keys
be
of the dictionary and the second contains the
stored. Often, the obvious way to write something values. If the table has multiple value columns,
down is similar to the table shown below. If the then these can be stored in separate
information in dictionaries using the same keys. You can,
the first column is unique (the items in it are not therefore, have one dictionary for budgets and
repeated), then using Python dictionaries might be the another for expenditure.
answer.
A dictionary is a data structure that consists of
multiple key:value pairs. It maps one value, such
as a name, to

500

200

50
The table information
above as a Python
PYTHON
Budget manager 1 W

Adding a budget
In this section, you will create budgets
for the various expenses. First, you will add
code to enable the user to add these budgets, and
then ensure that the code prevents users from
making some common budgeting errors.

ADD A BUDGET FUNCTION


Write a function to add a a vat I able
budget. The function will take the def add_budget(name, amount): will be global
name of the budget and the when set in
amount of money to be budgeted. global avai lable this function
It will then store these in the
Stores the
budgets dictionary and deduct the budgets[name] = amount budgeted
amount from the amount
available. The function then amount in
avai lable -= amount the budgets
returns the new available amount
dictionary
to show how much is still left expenditure[name] = 0
to budget. Add this code
below the global variables.
return available
Deducts the budgeted
amount from the Returns the Sets the spent
available amount new amount for this SAVE
available amount budget to 0

LED
RUN F
Save and then run the > > > add_budge t {" G roce r i es " , 500) Type this line
file
by selecting Run Module from the and press Enter
Run menu. This will open the IDLE
Python shell window. You can test 2000. 0 Returned value of
the function call
the function by typing an example
call in the shell. You will see >>> in > > > budgets
the window, which is the Python
shell prompt. You can type small { ' G roce r i es ' : 500}
pieces
of Python code next to this and > > > expend i ture
they will be executed when you
press Enter or return. { ' G roce r i es ' : 0}
Typing the name of
variables at the prompt
will show their values
NGO ERROR CHEC
To see what happens if you add a budget twice,
type this code in the shell window. You will notice that the

• budgets dictionary will be updated with the new value, but


the aval T able amount is reduced by both. To avoid this,
you need to add some code to check if the same budget
name has been used twice. Add the code shown in the Rent 900
editor window below to make changes to the Groceries 500
add_budget() function.

Clothes 300

> > > add_budget (" Rent " , 900)


1100. 0
> > > add_budget (" Rent" , 400)
The available amount
700. 0 is deducted twice

> > > budget s


{ ' Groce r i es ' : 500, Rent ' : 400}

Checks if name already


exists as a key in the
if name in budgets: budgets dictionary

ra i se Val ueE r ro r (" Budget exi st s") Leaves the function immediately
with an exception if a budget
name appears more than once

EXCEPTIONS

In Python, errors are indicated by raising exceptions.


There
These
areexceptions
a number interrupt
of standard
the exception
normal execution
types inof
Python.
code. Unless
Each ofthe
the

TYPES OF EXCEPTIONS
Name Use when
A value is not of the expected type: for example, using a string where a number was expected
TypeError

ValueEr ror A value is invalid in some way: for example, too large or too small

RuntimeError Some other unexpected error has occurred in the program


PYTHON
Budget manager 1 W K

check if the error has now


been fixed. When you run the
code, the three global var 2000.0
iables will be set back to their
initial values. Type this code > > > add_budget {"Rent" , 900)
in the shell window. You will
now 1100 . 0
get an error message if you
try adding the same budget » add_budget(”Rent“, 400)
twice. If you check the
variables budgets and aval Tr acebac k (most recent cat1 1ast) :
table, you will see that they
have not been updated with Fi ie "‹pyshell›", line 1, in
the wrong values. ‹module›
add_budget (” Rent “ , 400)
Error message
displayed on File "budget.py", line 7, in add_budget
screen
raise ValueError ("Budget exists")
VaI ueE r ror: Budget ext st s

> > > budgets


{ G roce r i es ' : 500, ' Rent : 900}

The variables >>> avai lable


will not be
updated with 1100 . 0
wrong values

MORE ERROR CHECKING


Continue in the shell window to see what happens if Update the code in the editor window. Then save
you budget an amount of money that is more than what is the file and run the code once again to test if
available. This is clearly an error, since you should not be able the new error message is displayed, and over-
to over-budget. Add another check into the add_budget () budgeting is prevented.
function to fix this.

>>> add_budget(“Clothes”, 2000)


A negative value
-900.0 indicates over-budgeting

Checks if the amount being


budgeted is more than the
if amount › avai lable: amount available

Raises an
raise ValueError(“Insufficient exception and
funds“) leaves the function
immediately
SAVE
>>> add_budget(“Groceries“, 500)
2000. 0
> > > add_budget (" Rent" , 900)
1100. 0
» add_budget("Clothes", 2000)
Traceback (most recent call
last):
File "‹pyshell›", line 1, in
Error message for
<module› add_budget("Clothes", over-budgeting
is displayed
2000)
File "budget.py", line 9, in add_budget
raise ValueError("Insufficient funds")
ValueError: Insufficient funds

Tracking expenditure
Next, you need to add a way to track
all the expenditure. To do this, you will
first add a function that allows you to enter
the money that has been spent,
and then add another function to 3' % “*. j. ‘\* RENT CLOTHES
GROCERIES ■ MONEY LEFT ■
display the summary. This will
indicate the total money spent
and the amount remaining.

ADD SPEND FUNCTION


Add a function to note the Raises an exception if the
amount you have spent and the name of value of name is not a
the budget that you want to track it key in the expendl tu re
against. def spend (name , aeount) :
dictionary
Add a new spend() function below the
add_budget() function. The Python
“+=” operator is used to add an if name not in expenditure:
amount to a variable. Save the file
and then run the module to try using raise ValueError(“No such budget“)
this new function.

Adds amount to the corresponding key expenditure[name] += amount


in the expend ture dictionary
PYTHON
Budget manager 1 64/
RETURNING THE REMAINING AMOUNT
It will also be useful to track the amount left in
the budget. Add this code to the end of the spend () > > > add_budget {" Groce r i es " , 500)
function you just created, then save and run the file to test
the code. 2000. 0
You will notice that you can spend more than the
budgeted amount. Vou do not need an exception for spend(“Groceries“, 35)
this, as you will want to track overspending.Gets the
budgeted
amount for name 46 s

budgeted = budgets[name] »> spend(“Groceries“, 15)


spent = expenditure[name] 45o
return budgeted - spent › spend(“Groceries“, 500)
Returns the amount Negative value indicates that
left in the budget Gets the —50 spending exceeds the budget
total amount
spent

ARK
In this step, you will add a function that will display an code at the bottom of the file. Then, save the
changes overview of each budget name, the amount originally budgeted, and run the file in the shell window.
The summary will the amount spent, and the amount left to spend (if any). Add this display the figures for
every category.

def print_summary():
Loops through all the
for name in keys in the budgets
dictionary Gets the budgeted amount
budgets:
budgeted = for the name key
Gets the amount spent
budgets[name] for the name key
spent =
expenditure[name]
Calculates the remaining amount
remaining = budgeted - spent by deducting budgeted from spent

print(name, budgeted, Prints a single line


I’ ma i n i ng)
spent, €'
summary for this budget

>>> add_budget(”Groceries“, 500)


2000.0
> > > add_budget {" Rent" , 900) __
1100 . 0 - -
> > > spend (" G roce r i es " , 35)
465 __
> > > spend "Groce r i es" , 15)
450
> > > pr i nt_summa ry {)
G roce r i es 500 50 450 Groce r 1es 500 50 450
Rent 900 0 900
Rent 900 0 900
HE SU ARK
At this stage, the summary will be a bit hard to the pr1 nt_summa ry() function as shown
below. read with the numbers squeezed together. To fix this, This will create a string from the values,
formatting you can line them up in a proper table by using “string each to a specific width and
number of decimal formatting” (see box, below). Change the pr1nt line in places. It will then
print that string.

pr i nt {f {name: 15s} {budgeted: 10.2f} {spent : 10.2f}


f ' { rema i ni ng: 10.2f} )
The amount will be displayed
with two decimal places

>>> add_budget(“Groceries“, 500)


2000
> > > add_budget (" Rent " , 900)
1100
> spend (" G roce r i es " , 35)
465
> spend (" G roce r i es " , 15)
450
> > > pr i nt_summa ry {) The values will have two
decimal places and will
G roce r i 500. 00 50 . 00 450 . 00 be lined up in columns,
similar to a table
es Rent 900. 00 0.00 900.00

L FORMAT STR NGS


In Python, formatted strings can be created from values EXAMPLES OF FORMAT STRINGS
with special format strings. These are written like
Result
normal strings, but have an “f” character before the
opening quotation mark. Inside the string, you can place f’(greeting} World!' ’Hello World! ’
code expressions within curly brackets. These will be
executed and replaced with their values. The most f’(greeting:J 0s)’ ’Hello
common expressions used are variable names, but
f'{cost:S.2f)' ’ 3.47’
arithmetic calculations can also be used. Any part of the
string outside the brackets is used without change. f’(cost:5.If)’ ’ 3.5’
Detailed formatting instructions can be added after a
colon. This includes f’The answer is (a * b)’ 'The answer is 42'
a letter specifying how to format the value. Placing
a number before this letter allows a width to be
specified.
PYTHON
Budget manager 1 W W

ADD A TABLE HEADER


Now, add a header to the table so that the numbers within each category can be easily distinguished.
Add two pr1n t statements in the
pr1n t_summar y() function. It may be easier to type the line with dashes first - 15 dashes followed by three lots of 10 dashes, with spaces in be

500.00 50.00 450.00

900.00 0.00 900.00

print(”Budget Budgeted Spent Remaining”)


print(”---------------
--
The titles have been aligned
against the dashes

AD A TABLE FOOTER
To complete the summary table, you can add a footer for printing the totals that you used for the budget.
to it. This will add up the contents of the various columns and However, remember to use “Total” instead of the
budget display their total value. Update the pr1nt_summar y() name, and totat_budgeted, totat_spent, and
function as shown below. Use the same format instructions totat_rema ln1ng for the other variables.

tot a1_budgeted = 0
tot a1_spent = 0 Sets the total
variables to 0
total_remaining =
0
tot a t_budge ted += budgeted
tot a t_spent += spent Adds the
amount to the
totals
total_remaining += remaining
print(”--------------------------------------------”)
print(f'{“Total“ :15s} {total_budgeted:10.2f} {total_spent:10.2f} '
f'{total_budgeted - total_spent:10.2f}')

Prints another
separator line
and the summary
» add_budget(“Groceries“, 500) with the totals
below it
2000. 0
> > > add_budget ("Rent" , 900)
1100. 0
>>> spend(“Groceries“, 35)
465
> spend {" G roce r i es" , 15)
450
>>> print_summary()

Budget Budgeted Spent Remaining

G roce r i es 500. 00 50 . 00 450 . 00


Rent 900 . 00 0 . 00 900 . 00

To ta I 1400. 00 50 . 00 1350 . 00
PYTHON @
Budget manager 1 W M

Converting the
code into a class
In this section, you will take all
the code written so far and turn it
into a Python class (see pp.156—
57).
This will allow the user to track
multiple budgets simultaneously.

NDEN THE ODES


Since Python is structured using Format Run Options Click here
to indentation, you need to indent the entire add indents
to
codetoconvertitintoaclasselectall IndentReQon ' the entire file
thecodeinthefiIeandthenchoose'ndent DedentRegion
Region" from the Format menu. Next, add Comment Out Region
a new class header at the top of the file,
before the variables.

Defines the c1 ass Budget Ilanage r:


new class

The variables will


now appear
indented

ERP
ADD N AL
Indent the three variables again and add a function values for the instance variables. The first argument of the
header to them. Functions inside a class are known as methods. initializer is the new instance, called self by
convention. The i nJt _ method is called when a new instance of a class You can also add additional arguments
that will allow you is created. This method is called the “initializer” as it sets the initial to provide useful values,
such as amount here.

Arguments
def init ( e a oun t) : within the
initializer
LED CREATE N ANCE VAR A
Next, convert the three variables into instance
variables. This is done by adding “self.“ before each of
the variable names. Use the argument amount instead
of 2500 as the initial value for the available instance
variable.
self amount
.
Converts the
variables to self.
instance variables
self.

TURN THE FUNCT ONS NTO E HODS


Now you need to turn all the other functions in the code into
methods. just like with the initializer, you can do this by adding self as
the first argument of every function, and then adding self. before each Remove the line
use of the instance variables. Modify the add_budget() function as shown global avaJ table
below. from between these
Delete the global avat \ able line from the add_budget method, as two lines of code
aval I able is now an instance variable.

self,
set f.

set f.

self.
self.
self.

set f
. set f
, set f .

set f .
set f .
set f .

Adds an argument
(self): to the function
PYTHON
Budget manager 1 70/ 1 / 1

self .
set f
. set f .

Add self. before


each use of the
instance variable
SAVE

RUN HE ODULE
Save and run the module. Type these lines in the shell
window to test the code. This will add a newly created instance of the
BudgetManager class. The code inspects the instance variables by Sets the variable outgoings
putting outgoings . before their name. You can call methods in a to an instance of the
similar way, by putting the variable name before the function name BudgetManager class
with a full stop.

» outgoings = BudgetManager(2000)
>>> outgoings.avai lable
2000
> outgoings.budgets

» outgoings.expenditure

> > > outgoi ngs . add_budget {" Rent" , 700)


1300
> outgoings.add_budget(“Groceries“, 400)
900
>> outgoings.add_budget(“Bills”, 300)
600
» outgoings.add_budget(“Entertainment”, 100)
500
» outgoings.budgets
{'Rent': 700, 'Groceries' : 400, 'Bills': 300, 'Entertainment': 100}
>>> outgoings.spend(“Groceries”, 35)
365
> > > outgoi ngs . pr i n t_summa ry {)
Budget Budgeted Spent Rema i ni ng

Rent 700. 0.00 700.00


G roce r i es 00
35.00 365.00
Bills 400.
0.00 300.00
E n te rt a i 00
nment 0.00 100.00
300.
00

Total 100. 35.00 1465. 00


00

1500.00

SQ RAC N MUL PLE BUDGE


It is possible to reset the budget by simply creating a budget called hold day. As the available, budgets, and
new instance of the BudgetManager class, by typing this code inexpenditure variables are stored within each instance,
the shell window. You can even have multiple BudgetManager they are distinct from each other and can have
different instances for tracking separate budgets. To test this, create a new values for the different instances.

Creates a new instance of


the Budgets anager class

» outgoings = BudgetManager(2500)
>>> outgoings.add_budget(“Groceries“, 500)
2000 Prints the summary
for the new instance
>>> outgoings.print_summary()
PYTHON
Budget manager 1 72/

Budget Budgeted Spent Remaining

Groce r i 500 . 0 . 00 500 .


es 00 00

To ta 1 500 . 00 0 . 00 500 . 00
>>> holiday = BudgetManager(1000)
Addsanoher
nevvinstanceof
> > > hot i day . add_budget {" F1 i ght s" , 250) BudgetManager
750
> > > hot i day . add_budget {"Hotel " , 300)
450
> holiday.spend(”Flights”, 240)
10
»> holiday.print_summary()
Budget Budgeted
Spent Remaining

Flights 250. 00 240. 00 10. 00


Hotel
300. 00 0 . 00 300 . 00

To ta I 550 . 00 240 . 00 310 . 00

EQ U NG THE CO
The code written in this project is a module that can new file and save it in the BudgetManager folder you
be used in other programs. This module can be imported and created earlier. Name this new file "test.py".
Now add used like any other Python library (see pp.116—17). Try this out this code to create an instance of the
BudgetManager by creating a new module that will import this one. Open a class that calls methods on
it.

Imports the module


import budget budget into this new
one
outgoings = budget.BudgetManager(2500)
The BudgetManager
class is referenced by
outgoings.add_budget(“Groceries“, 500) adding the budget
outgoings.print_summary() module name before
it with a full stop
•• Hacks and tweaks
Changing your mind
In the project, you modified the add_budget method to
stop the same budget from being added twice. However, it below the existing add_budget method. You
would also be useful to have a way to change a budget may need to look at this code carefully to
later. You can add a new method to do this. Add the follow the logic. Add a line in the test.py
following new method module to call this new method so that you
can see it working.

def change_budget(self, name, new_amount): Checks if the


budget to be
if name not in self.budgets: changed exists
raise ValueError(“Budget does not Gets the old
amount of
exist”) old_amount = self.budgets[name] the budget

if new_amount › old_amount + Checks if the old


amount added
self.available: raise to the available
amount covers
ValueError(“Insufficient funds“) the new amount
Updates the
self.budgets[name] = new_amount
bud
self.available -= new_amount -
old_amount return self.avai lable
e b
' Rh dd eeranae babwee the
old and the new amounts

Record expenditure details


So far, the project tracks the total expenditure against each budget.
However, in a more advanced program you would want to keep
track of each particular item of expenditure. You can do this by
using lists of amounts spent inside the expend i ture dictionary
and then adding these together whenever you need the total.

SQ CREA E AN EXPEND URE L


Start by modifying the expendi ture
dictionary in the add_budget method. Vou
need to store an empty list inside expend1ture,
instead of 0. This allows multiple values to be self.expenditure[name] = []
stored in it.

Stores an
empty list
74
PYTHON 0
Budget manager 1

TQ AD EXPEN E 0L
” Now in the spend method, change the expend1tu
re variable so that each new expense is added to the list.
Since expendl tu re no longer sums up the amounts spent
automatically, you will have to modify the spent variable to
perform the calculations and get the total spent so far.

self.expenditure[name].append(amount) Appends the


amount to the list

spent = sum(self.expenditure[name])

GEuTo ALEX END TUp RE


p n u a y
method. Modify the spent variable as shown below. Yo will find
that the code functions identically if you run the “test.py“ module
again, with a record for each item of expenditure.

Gets the amount spent


spent = sum(self.expenditure[name]) for each budget

You might also like