User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 392,308 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,864 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser:

Starting Python

Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,394
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 9
Solved Threads: 172
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #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 : Mar 1st, 2007 at 3:09 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
All times are GMT -4. The time now is 10:07 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC