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
+ 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
 temps.txt (729 Bytes, 209 views)
Aug 31 '11 #1
Share this Question
2 Replies

 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 #!/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 Sep 14 '11 #3

### Post your reply

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