What is wrong with my little 20-line program?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Alan Stewart
    New Member
    • Aug 2011
    • 2

    What is wrong with my little 20-line program?

    temps.txt
    Code:
    # TEMPERATURE CONVERSIONS / temps.txt / 09/01/2011
    # CELSIUS / FAHRENHEIT / CONVERSIONS       
    # Alan Stewart  /  1-(361)-980-1877
    #                                                
    #!/usr/local/bin/python
    import string, sys
    # if no arguments were given,print a helpful message.
    if len (sys.argv) == 1:
        print'Usage: celsius temp1 temp2  ...'           
        sys.exit(0)                
    # Loop over the arguments              
    for i in sys.argv[1:]:
        try:        
            fahrenheit=float(string.ato1(i))
        except string.atoi_error:
            print repr(i), "Not a numeric value."
        else:
            celsius=(fahrenheit-32)*5.0/9.0
            print '%iF=%iC' %(int(fahrenheit),int(celsius+0.5))
    Attached Files
    Last edited by bvdet; Aug 31 '11, 07:33 PM. Reason: Add code tags
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    You misspelled string.atoi

    Comment

    • Dev Player
      New Member
      • Jan 2011
      • 6

      #3
      Try it like this:

      Code:
      #!/usr/local/bin/python
      
      # TEMPERATURE CONVERSIONS / temps.txt / 09/01/2011
      # CELSIUS / FAHRENHEIT / CONVERSIONS
      # Alan Stewart  /  1-(361)-980-1877
      #              
      
      import sys
      
      # If no arguments were given,print a helpful message.
      if len(sys.argv) <= 1:
          print('Usage: celsius temp1 temp2  ...')
          sys.exit(0)             
      
      # Loop over the arguments
      for i in sys.argv[1:]:
          try:
              fahrenheit=float(i)
          except ValueError:
              print('%s is not a numeric value.' % repr(i))
          else:
              celsius=(fahrenheit-32)*5.0/9.0
              print('%iF=%iC' % (int(fahrenheit), int(celsius+0.5)))
      I removed the space between len and (sys.argv), changed print to Python 3.0 format, removed import string as float('1.0') or float('5') converts to a float and a ValueError is raised when float('a') or some such thing is entered. also moved the #!/usr/local/bin/python
      comment to line 0 (line1) as unix looks for that line there.

      I noticed you do a sys.exit(0) if the app doesn't receive the right commandline parameters. However this is typically the return value if the program ran 100% correctly. You may want to do a sys.exit(1) there. And for consistancey sake do a sys.exit(0) at the bottom of the temps.py
      Last edited by Niheel; Sep 14 '11, 04:20 PM. Reason: Easier to understand that code is reference if in same post

      Comment

      Working...