[Tutor] Class Tips

David david at abbottdavid.com
Sun May 31 21:08:08 CEST 2009


W W wrote:

> 
> One thing that's probably not in the scope of the program but really 
> usually a good idea is error checking.
> i.e.  this line:
> rate = float(raw_input("Enter rate i.e. (0.5) : "))
> 
> could be converted to something like:
> 
> try:
>     rate = float(raw_input("Enter rate..."))
> except ValueError:
>     print "Invalid input"
>     #Quit or loop until valid input is entered.
> 
> HTH,
> Wayne
OK, this is what I came up with, how else could I do it so as not to use 
sys.exit() ?

#!/usr/bin/python
"""Determine the number of bags to use to fertilize
a given area given the application rate."""
from sys import exit

class FertRate:
     def __init__(self, rate, nitrogen, acre, bag):
         self.area = 43.560
         self.app = rate / (nitrogen / 100.00)
         self.acre = acre
         self.bag = bag

     def result(self):
         result = self.app * self.area * self.acre / self.bag
         return result

def main():
     while True:
         try:
             frate = FertRate( *get_inputs() )
             result = frate.result()
             print 'You should apply %0.2f bags.' % result
             exit()
         except TypeError, UnboundLocalError:
             pass

def get_inputs():
     try:
         print 'Rate: Pounds nitrogen per 1000 (square feet)'
         rate = float(raw_input('Enter Rate i.e., (0.5): '))
         print "Nitrogen: The first number of the fertilizer's analysis"
         nitrogen = float(raw_input('Enter Nitrogen From Bag i.e., (14): '))
         acre = int(raw_input("Enter Total Acre's To Be Treated i.e, 
(3): "))
         bag = int(raw_input('Enter Bag Weight (lb): i.e., (50) '))
         return rate, nitrogen, acre, bag
     except ValueError:
         print 'Invalid input!'
         print 'You must enter a number!'

if __name__ == "__main__":
     main()


-- 
Powered by Gentoo GNU/Linux
http://linuxcrazy.com


More information about the Tutor mailing list