Professional Documents
Culture Documents
Abano
Abano
Abano
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
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
°°
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.
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
Clothes 300
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
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
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.
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
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()
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.
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.
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 .
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
1500.00
» outgoings = BudgetManager(2500)
>>> outgoings.add_budget(“Groceries“, 500)
2000 Prints the summary
for the new instance
>>> outgoings.print_summary()
PYTHON
Budget manager 1 72/
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
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.
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.
spent = sum(self.expenditure[name])