By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,941 Members | 1,753 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,941 IT Pros & Developers. It's quick & easy.

What is wrong with my little 20-line program?

P: 2
temps.txt
Expand|Select|Wrap|Line Numbers
  1. # TEMPERATURE CONVERSIONS / temps.txt / 09/01/2011
  2. # CELSIUS / FAHRENHEIT / CONVERSIONS       
  3. # Alan Stewart  /  1-(361)-980-1877
  4. #                                                
  5. #!/usr/local/bin/python
  6. import string, sys
  7. # if no arguments were given,print a helpful message.
  8. if len (sys.argv) == 1:
  9.     print'Usage: celsius temp1 temp2  ...'           
  10.     sys.exit(0)                
  11. # Loop over the arguments              
  12. for i in sys.argv[1:]:
  13.     try:        
  14.         fahrenheit=float(string.ato1(i))
  15.     except string.atoi_error:
  16.         print repr(i), "Not a numeric value."
  17.     else:
  18.         celsius=(fahrenheit-32)*5.0/9.0
  19.         print '%iF=%iC' %(int(fahrenheit),int(celsius+0.5))
Attached Files
File Type: txt temps.txt (729 Bytes, 209 views)
Aug 31 '11 #1
Share this Question
Share on Google+
2 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
You misspelled string.atoi
Aug 31 '11 #2

P: 6
Try it like this:

Expand|Select|Wrap|Line Numbers
  1. #!/usr/local/bin/python
  2.  
  3. # TEMPERATURE CONVERSIONS / temps.txt / 09/01/2011
  4. # CELSIUS / FAHRENHEIT / CONVERSIONS
  5. # Alan Stewart  /  1-(361)-980-1877
  6. #              
  7.  
  8. import sys
  9.  
  10. # If no arguments were given,print a helpful message.
  11. if len(sys.argv) <= 1:
  12.     print('Usage: celsius temp1 temp2  ...')
  13.     sys.exit(0)             
  14.  
  15. # Loop over the arguments
  16. for i in sys.argv[1:]:
  17.     try:
  18.         fahrenheit=float(i)
  19.     except ValueError:
  20.         print('%s is not a numeric value.' % repr(i))
  21.     else:
  22.         celsius=(fahrenheit-32)*5.0/9.0
  23.         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
Sep 14 '11 #3

Post your reply

Sign in to post your reply or Sign up for a free account.