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
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:
main() to convert()
convert() explicitlyexit() to returns, and call exit() in the main clause.argv for length 2, when you should have been checking args.to_c and to_f functions don't need a temp variable, just return the expression.if __name__ style, so that you could import this module and use the functions in other code.args[1] appears enough that I assigned it to t for brevity.sys.argv, for example.if blah: doit()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With