School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 307,130 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 2,025 people online right now. Registration is fast and FREE... Join Now!




Budget planner using python

 

Budget planner using python, I need help with the code for keepig it from crashing if the wrong inp

Dcaldwell

29 Aug, 2009 - 12:13 AM
Post #1

New D.I.C Head
*

Joined: 28 Aug, 2009
Posts: 1

CODE
def main():
    choice = 0
    income = 4000
    global maxincome
    maxincome = 4000

    outFile = open('bh.txt', 'w')
    outFile = open('bh.txt', 'a')
    print >> outFile, '**Detailed budget history:-'
    print >> outFile
    print >> outFile, 'Starting balance: ',maxincome

    inFile = open('bh.txt', 'w')
    inFile = open('bh.txt', 'a')
    print >> inFile, '**Detailed budget history:-'
    print >> inFile
    print >> inFile, 'Starting balance: ',maxincome
    
    userInput = raw_input('Welcome to the financial planner. Press enter to continue: ')
    if userInput != "":
            choice=int(userInput)
    while choice <> 999:
        choice = menu(choice)
        if choice == 1:
            income, amt = addExp(income)

            outFile = open('bh.txt', 'a')
            print >> outFile, 'Expense Added =',amt,'Available Income:',income

        elif choice == 2:
            income, amt = removeExp(income)

            outFile = open('bh.txt', 'a')
            print >> outFile,'Expense Removed =',amt,'Available Income:',income

        elif choice == 3:
            income, amt = addIncome(income)

            outFile = open('bh.txt', 'a')
            print >> outFile,'Income Added =',amt,'Availabe Income:',income
            
        elif choice == 4:
            income, amt = removeIncome(income)

            outFile = open('bh.txt', 'a')
            print >> outFile,'Income Removed =',amt,'Availabe Income:',income
            
        elif choice == 5:
            inFile = open('bh.txt', 'r')
            displayBudgetHistory(income, inFile)

        elif choice == 999:
            print '**Thanks for using the budget utility...'

        else: print '***Invalid selection'
        
    outFile.close()
    inFile.close()

def addExp(income):
   print
   amt = input('**Enter expense to add: ')
   print

   if (amt <= income and amt > 0):
       print '**Funds before adding adding expense: ',income
       income = income-amt
       print '**Funds after adding expense: ', income
       return (income, amt)
   elif amt > income:
       print '**Insufficient funds. Cant add this expense: ',income, 'Expense: ',amt
   else: print '**Invalid entry'

def removeExp(income):
   print
   amt = input('**Enter expense amount to be removed: ')
   print
  
   global maxincome

   if (amt + income <= maxincome):
       print '**Funds before removing the expense: ',income
       income = income + amt
       print '**Funds after removing expense: ',income

   elif ((amt + income) > maxincome):
       print '**Unable to remove expense. Invalid expense: ',income,' < Expense: ',amt
          
   else: print '**Invalid Expense'

   return(income, amt)

def addIncome(income):
    print
    amt = input('**Enter income to add: ')
    print

    if (amt <= income and amt > 0):
       print '**Funds before adding income: ',income
       income = income + amt
       print '**Funds after adding income: ',income
       return (income, amt)
    

def removeIncome(income):
    print
    amt = input('**Enter income amount to be removed: ')
    print
  
    global maxincome

    if (amt - income <= maxincome):
       print '**Funds before removing the income: ',income
       income = income - amt
       print '**Funds after removing income: ',income

    elif ((amt + income) > maxincome):
       print '**Unable to remove income. Invalid income: ',income,' < Income: ',amt
          
    else: print '**Invalid income'

    return(income, amt)


def displayBudgetHistory(income, inFile):

   print
   text = inFile.read()
   print text

  
def menu(choice):
  

   print '-:MAIN MENU:-'; print;
   print '1:  <---Add Expense'
   print '2:  <---Remove Expense'
   print '3:  <---Add Income'
   print '4:  <---Remove Income'
   print '5:  <---Display Transaction History'; print;
   print '999:  <---Exit'; print;

   choice = ""
   while choice == "":
       choice = raw_input('***Enter a selection: ')

   return int(choice)
   print

main()


I am able to run the program fine. The only problem is its not crash resistant. I have researched for three weeks trying to find an answer but have been unable to come up with one. Can anybody help me with this? I have already tried using the try: exception method, but I may have written it incorrectly. Any help would be greatly appreciated.



User is offlineProfile CardPM
+Quote Post


Nallo

RE: Budget Planner Using Python

29 Aug, 2009 - 06:22 AM
Post #2

New D.I.C Head
*

Joined: 19 Jul, 2009
Posts: 24



Thanked: 3 times
My Contributions
You may want to tell us, how you crashed your programm and what error message you got then. It is a little difficult to help you without that information.

Anyway, one way to handle user input with the try except satement would be as follows:
CODE
while True:
    user_input = raw_input("enter some value")
    try:
        data = int(user_input) #or float(...) for floats
    except ValueError:
        print "invalid input, try again"
    else:
        break
# data is an integer when the loop is left

Explanation: if int(user_input) fails, a ValueError Exception is thrown, and caught in the except block. If no exception is caught the else block is executed and break command leves the while loop, data is an integer.
If an exception was caught, the else block is not executed and the loop continues.

One more important comment on your code:
Dont use input(). Use raw_input() instead.

Input is not safe. For example look at the following code:
CODE
#DONT TRY THIS AT HOME, KIDS
import os
user_input = input("crash me please")

What happens, if a user inputs os.system("rm file")?

With input() Python tries to evaluate whatever is entered as a python expression ... So Python calls the os.system function with the argument "rm file", which in turn executes the shell command "rm file" and removes file from your disk. For a real headache, assume it was "cd /;rm -r *" on Linux and your programm run with root rights.

This post has been edited by Nallo: 29 Aug, 2009 - 05:20 PM
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/21/09 02:34PM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month