One more function sample to show you that a function can decide internally what type of number to return. Also shows an example of try/except exception handling.
# a function to return the numeric content of a cost item
# for instance $12.99 or -$123456789.01 (deficit spenders)
def getVal(txt):
if txt[0] == "$": # remove leading dollar sign
txt = txt[1:]
if txt[1] == "$": # could be -$xxx
txt = txt[0] + txt[2:]
while txt: # select float or integer return
try:
f = float(txt)
i = int(f)
if f == i:
return i
return f
except TypeError: # removes possible trailing stuff
txt = txt[:-1]
return 0
# test the function ...
print( getVal('-$123.45') )
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor without the line numbers.
Last edited by vegaseat; Aug 16th, 2009 at 10:15 pm. Reason: [code=python] tag
May 'the Google' be with you!