[Tutor] Help - 2nd validator won't work

Noah Hall enalicho at gmail.com
Sat Apr 16 09:48:20 CEST 2011


On Sat, Apr 16, 2011 at 4:33 AM, Lea Parker <lea-parker at bigpond.com> wrote:
>     budget = float(raw_input('Enter the amount of your budget for the month:
> '))
>
>     # Validation variable for budget
>
>     while budget <0:
>
>         print 'ERROR: the budget cannot be a negative amount'
>
>         budget = float(raw_input('Enter the correct budget for the month:
> '))
>

This is alright, but it still allows users to enter 0 for the budget


>     expense = float(raw_input('Enter your first expense '))
>
>     total_expense += expense

This is where you're going wrong. You don't validate the expense here
at all before adding it to total_expense.

>     # Continue processing as long as the user does not enter 0
>
>     while expense != 0:
>         #Get another expense
>
>         expense = float(raw_input('Enter expense or 0 to finish '))
>
>         total_expense += expense
>
>         while expense <0:
>
>             print 'ERROR: the budget cannot be a negative amount'
>
>             expense = float(raw_input('Enter the correct budget for the
> month: '))
>
>             total_expense += expense

Same again here as above.

>     #Calculate surplus
>
>     budget_difference = budget - total_expense
>

Now, given that total_expense could be negative, you'll end up with a
budget_difference that is in fact larger than the budget - crazy, I
know.

> # Call the main function.
>
> main()

It's also good practise to use
if __name__ == '__main__':
    main()
So that you can then use this script for a module later on.

HTH


More information about the Tutor mailing list