Python – Temperature Convertor

Below is a small script to convert temperatures between celcuis and fahrenheit (and vice versa). This article / script is meant as reference point rather than a full tutorial.

#!/usr/bin/python

import sys

def convert(t,fc):
        if t == “2f”:
                print (fc * 9) / 5 + 32,”Degress Fahrenheit”
        elif t == “2c”:
                print (fc – 32) / 9 * 5,”Degress Celcuis”

def usage():
        print ”’\
Usage: convert-temp [TEMP] [TYPE]
This program coverts the temperatures celcius and fahrenheit.
Options include:
    –version   : Prints the version number
    –help      : Display this help

Examples:
    convert-temp 33 2f    Convert to fahrenheit
    convert-temp 80 2c    Convert to celcuis”’
try:
        if sys.argv[1].startswith(‘–‘):
                option = sys.argv[1][2:]
                # fetch sys.argv[1] but without the first two characters
                if option == ‘version’:
                        print ‘Version 0.1’
                elif option == ‘help’:
                        usage()
                else:
                        print ‘Unknown option.’
                sys.exit()
        elif len(sys.argv) < 3:
                print ‘Insufficient Parameters.’
        else:
                type = sys.argv[2]
                temp = int(sys.argv[1])
                convert(type,temp)
except:
        usage()

Rick Donato

Want to become a programming expert?

Here is our hand-picked selection of the best courses you can find online:
Python Zero to Hero course
Python Pro Bootcamp
Bash Scripting and Shell Programming course
Automate with Shell Scripting course
The Complete Web Development Bootcamp course
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial