Several improvements in Ned's answer. In Python2.7 / , the result is truncated by default, so you need to import division from __future__ , otherwise (c * 9/5) + 32 always rounded, which leads to a decrease in accuracy.
for example, if 36C is 96.8F, it is better to return 97 than 96
You do not need the return statement in convert . By default, None returned. If there is a problem, you can throw an exception
Also using "".format() now preferable
A further improvement would be to use optparse or similarly handle command arguments, but may be redundant for such a simple program
from __future__ import division import sys def to_f(c): # Convert celsius to fahrenheit return (c * 9/5) + 32 def to_c(f): # Convert fahrenheit to celsius return (f - 32) * 5/9 def convert(args): if len(args) != 2: raise RuntimeError("List of two elememts required") t = int(args[1]) if args[0] == '-f': # If the first argument is -f print "{0} Fahrenheit is {1} Celsius".format(t, round(to_c(t))) elif args[0] == '-c': # If the first argument is -c print "{0} Celsius is {1} Fahrenheit".format(t, round(to_f(t))) else: raise RuntimeError("First element should be -c or -f") if __name__ == '__main__': sys.exit(convert(sys.argv[1:]))
source share