Thread: Starting Python
View Single Post
Join Date: Oct 2004
Posts: 3,862
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 870
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #7
Mar 27th, 2005
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.
  1. # a function to return the numeric content of a cost item
  2. # for instance $12.99 or -$123456789.01 (deficit spenders)
  3. def getVal(txt):
  4. if txt[0] == "$": # remove leading dollar sign
  5. txt = txt[1:]
  6. if txt[1] == "$": # could be -$xxx
  7. txt = txt[0] + txt[2:]
  8.  
  9. while txt: # select float or integer return
  10. try:
  11. f = float(txt)
  12. i = int(f)
  13. if f == i:
  14. return i
  15. return f
  16. except TypeError: # removes possible trailing stuff
  17. txt = txt[:-1]
  18. return 0
  19.  
  20. # test the function ...
  21. 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!
Reply With Quote