[Tutor] Help - accumulator not working (Lea)

Alan Gauld alan.gauld at btinternet.com
Sat Apr 16 01:27:22 CEST 2011


"Lea Parker" <lea-parker at bigpond.com> wrote

> I am trying to create this program for a uni assignment. I cannot 
> get it to
> add the expenses to the accumulator I have set.

You have to write the code to add each value to the accumulator
Your loop does not do that....

> """This program is to calculate if the user is over or under budget
>
> for the month"""
>
>
>
>

Wow! Thats a lot of whitespace.
It is good to separate code blocks into logical segments
with whitespace, but too much of it just makes the code
flow hard to see. In the old days of green screen terminals
on mainframes they used to say that a function should
all fit on a single screen - 24 lines. Nowadays we don't
need to be quite so penny pinching, but the concept of
seeing the whole flow in one place is a good one.

I'll remove some excess space below...

> def main():
>    # Create an accumulator

Oh, and if you can use a good variable name to describe
the variable you don't need a comment either - It's just
more distracting wasted space. Comments are to explain
*why* (and occasionally, for the really obscure, how), but
good names describe what.

>    total_expense = 0.0
>    budget = float(raw_input('Enter the amount of your budget for the 
> month:'))
>
>    # Calculate a series of expenses

I left this comment because it explains why we have a loop...

>    expense = float(raw_input('Enter your first expense $'))
>    total_expense = total_expense + expense
>    while expense != 0:
>        expense = float(raw_input('Enter the next expense or 0 to 
> finish'))
>        surplus = budget - total_expense
>
>    print 'Your total expenses for the month $', total_expense
>    print 'Your surplus amount after expenses $', surplus
>
> main()

Hopefully that makes it easier to see what you missed out?

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list