Ive written a small program to convert celcuis o Fahrenheit and vice versa.
The script as it stands works :

``````#!/usr/bin/python

import sys

def convert(t,fc):
if t == "c":
print (fc * 9) / 5 + 32,"Degress Fahrenheit"
elif t == "f":
print (fc - 32) / 9 * 5,"Degress Celcuis"

if len(sys.argv) < 3:
print 'Insufficient Parameters.'
sys.exit()
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':
print '''\
This program coverts the temperatures celcius and farenheit.
Options include:
--version   : Prints the version number
--help      : Display this help'''
else:
print 'Unknown option.'
sys.exit()
else:
type = sys.argv[1]
temp = int(sys.argv[2])
convert(type,temp)``````

But if instead of using the int(sys.argv[2]) to convert the string to an intergar, I use string formatting such as .. (shown below) i get the error :

TypeError: unsupported operand type(s) for %: 'int' and 'str'

``````def convert(t,fc):
if t == "c":
print ("%d" * 9) / 5 + 32,"Degress Fahrenheit" % (fc)
elif t == "f":
print ("%d" - 32) / 9 * 5,"Degress Celcuis" % (fc)``````

Shouldn't the string format convert the fc to a decimal int ?

Thanks,

It would be better to compute with floating numbers to avoid division issues (like 5/9 == 0)

``````def nearest_int(number):
return int(number + (0.5 if number >= 0 else -0.5))

print "%d Degrees Farenheit" % nearest_int(float(fc) * 9 / 5 + 32)``````

Also it would be much better to use the optparse or argparse module to handle command line arguments and options. Read this tutorial http://www.alexonlinux.com/pythons-optparse-for-human-beings

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.