Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning Python, is there a better way to write this?

Tags:

python

I am learning Python (2.7) and to test what I have learned so far I wrote a temperature converter that converts Celsius to Fahrenheit and I wanted to know if my code could be written better to be faster or something more Pythonic. And could someone tell me if there is an actual name for the if __name__ == '__main__': main() (out of curiosity)?

from sys import argv, exit # import argv and exit functions

def to_f(c): # Convert celsius to ferinheight
    temp = (c * 9/5) + 32
    return temp

def to_c(f): # Convert ferinheight to celsius
    temp = (f - 32) * 5/9
    return temp

def main():
    args = argv[1:] # Creates an argument list omitting the omitting the [0] element
    if len(argv) < 2: exit(1) # If less than two arguments
    if args[0] == '-f': # If the first argument is -f
        print args[1], 'ferinheight is', str(to_c(int(args[1]))), 'celsius'
    elif args[0] == '-c': # If the first argument is -c
        print args[1], 'celsius is', str(to_f(int(args[1]))), 'ferinheight'
    else: exit(1)

if __name__ == '__main__':
    main()

http://pastebin.com/rjeNikDt

like image 212
Dr Hydralisk Avatar asked Dec 02 '22 05:12

Dr Hydralisk


1 Answers

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:
        return 1 # If less than two arguments
    t = args[1]
    if args[0] == '-f': # If the first argument is -f
        print "%s Fahrenheit is %s Celsius" % (t, to_c(int(t)))
        return 0
    elif args[0] == '-c': # If the first argument is -c
        print "%s Celsius is %s Fahrenheit" % (t, to_f(int(t)))
        return 0
    else:
        return 1

if __name__ == '__main__':
    sys.exit(convert(sys.argv[1:]))

What I did:

  1. Changed the name of main() to convert()
  2. Pass the arguments to convert() explicitly
  3. Change calls to exit() to returns, and call exit() in the main clause.
  4. You were checking argv for length 2, when you should have been checking args.
  5. The to_c and to_f functions don't need a temp variable, just return the expression.
  6. Although others are right that you can just put the main() function at the top level, it is good form to use the if __name__ style, so that you could import this module and use the functions in other code.
  7. String formatting is nicer than intermixing strings and values in the print statement.
  8. args[1] appears enough that I assigned it to t for brevity.
  9. I prefer importing sys, and using sys.argv, for example.
  10. I always put dependent clauses on new lines, never if blah: doit()
  11. Fix the spelling of Fahrenheit
like image 135
Ned Batchelder Avatar answered Dec 05 '22 17:12

Ned Batchelder