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,

Dani AI

Generated

The error happens because string-formatting with % does not magically convert text into numbers, and the % operator is overloaded (string formatting when the left operand is a string, numeric remainder when the left operand is a number). In the broken line the arithmetic and the %/parentheses end up applied to the wrong objects, so Python sees incompatible types. Also note that in older Python versions dividing two ints does integer division (5/9 == 0) unless a float is used or from __future__ import division is enabled.

A simple, clear pattern fixes the problem: convert the command-line text to a number first, do all numeric math, then format the numeric result into a string. Example (Python 3 style):

def convert(scale, fc):
    val = float(fc)
    if scale.lower().startswith('c'):
        result = val * 9.0 / 5.0 + 32.0
        print("{:.0f} Degrees Fahrenheit".format(result))
    else:
        result = (val - 32.0) * 5.0 / 9.0
        print("{:.0f} Degrees Celsius".format(result))

Extra notes and small gotchas: avoid naming a variable type (it hides the built-in). Use float() for arithmetic then round() or format specifiers for desired display (the example uses :.0f for zero-decimal rounding). Add a try/except around the conversion to catch non-numeric input. For scripts intended for real use, prefer a command-line parser (as suggested) rather than manually indexing sys.argv. This approach prevents the TypeError seen by and yields correct results across Python versions.

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.