[Tutor] Class Tips
Alan Gauld
alan.gauld at btinternet.com
Sun May 31 22:16:59 CEST 2009
"David" <david at abbottdavid.com> wrote
> OK, this is what I came up with, how else could I do it so as not to use
> sys.exit() ?
You don;t need the exit(), The program will just drop off the end
silently without it. Thre are several other redundant bits you could
just miss out:
> 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
leave out the variable and just return the calculated value:
return self.app * self.area * self.acre / self.bag
> def main():
> while True:
> try:
> frate = FertRate( *get_inputs() )
> result = frate.result()
> print 'You should apply %0.2f bags.' % result
And here miss the variable and use the functin in the format string:
print 'You should apply %0.2f bags.' % frate.result()
> exit()
And just delete this.
> 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!'
You could put the whole thing in a while loop so the error gets
printed but the user has a chance to corect it.
def get_inputs():
while True:
try:
# blah blah
return ..... # breaks from the while loop
except ValueError, TypeError:
print blah
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list