Hello, this is my first post in this forum. I recently decided to try my hand at programming with python. I'm completely new to programming so I thought I should try some simple projects to reinforce what I've learned so far.

I saw a post from 3 years ago on this forum about a unit converter that has to work with inches, feet, miles, millimeters, centimeters, meters, and kilometers, and thought it would be a good project to try. So far I've only written enough script to convert from inches to any of the units mentioned above. I've got the feeling I'm going about this in the wrong way, so I wanted to see what you guys think about the code I've written so far before i go any further.

Please let me know if the way I'm writing this is wrong, or if there might be a better/more efficient way of writing this program.

def main():
  start = raw_input ("Convert from? ")
  if start == "inches":
    return inches()
  elif start == "feet":
    return feet()
  elif start == "miles":
    return miles()
  elif start == "millimeters":
    return millimeters()
  elif start == "centimeters":
    return centimeters()
  elif start == "meters":
    return meters()
  elif start == "kilometers":
    return kilometers()
  else:
    return main()

def inches():
  end = raw_input("Convert to? ")
  value = input("Value? ")
  feet1 = value / 12.0
  miles1 = value / 63360.0
  millimeters1 = value * 25.4
  centimeters1 = value * 2.54
  meters1 = value * 0.0254
  kilometers1 = value * .0000254
  if end == "feet":
    print "\n\n", feet1, "feet\n\n"
    return main()
  elif end == "miles":
    print "\n\n", miles1, "miles\n\n"
    return main()
  elif end == "millimeters":
    print "\n\n", millimeters1, "millimeters\n\n"
    return main()
  elif end == "centimeters":
    print "\n\n", centimeters1, "centimeters\n\n"
    return main()
  elif end == "meters":
    print "\n\n", meters1, "meters\n\n"
    return main()
  elif end == "kilometers":
    print "\n\n", kilometers1, "kilometers\n\n"
    return main()
    
  
main()

You have an infinite loop because all of the returns call main() again. BTW main is a bad name for a function because it is not descriptive. Some instructors use it in their beginning courses so as to not confuse the students with functions that have different names. In your case main() serves no purpose as you can just run the code without it. If you know lists, you can reduce a lot of the redundant code using a list.

def inches(start):
    convert_to = [["feet", 0], ["miles", 0], ["millimeters",0],
                  ["centimeters", 0], ["meters", 0], ["kilometers", 0]]
    for item in convert_to:
        print item[0]
    end = raw_input("Convert to? ")
    value = input("Value? ")
    convert_to[0][1] = value / 12.0      ## feet
    convert_to[1][1] = value / 63360.0   ## miles
    convert_to[2][1] = value * 25.4      ## etc
    convert_to[3][1] = value * 2.54
    convert_to[4][1] = value * 0.0254
    convert_to[5][1] = value * .0000254
    for item in convert_to:
        if end == item[0]:
            print "%s to %s, %7.2f = %7.2f" % (start, end, value, item[1])
start = raw_input ("Convert from? ")
inches(start)

Finally, the usual strategy is to convert everything to a common base and then convert from that common base to the desired unit, so there is one function that converts everything to inches or millimeters and passes that value to the conversion function, which reduces code in the remaining functions as they only have one unit to convert.

Edited 4 Years Ago by woooee: n/a

Thank you for the quick reply! I figured there was something I wasn't using that could reduce the amount of code. I don't fully understand the code you wrote yet, but I'll read up on how to use lists and try to figure it out by myself.

I appreciate you taking the time to help me and sending me the link for lists. If I have more questions would it be alright to PM you or ask you here?

The DaniWeb policy is to keep discussions public so others in same situation may benefit. It is usefull to continue and learn also to use dictionaries.

Here unit conversion with them:

units = dict(mm=1., cm=10., m=1000., km=1000000., inch=254., ft=3048., mile=1609344.)

while True:
    request = raw_input('\nGive amount and unit e.g. 125 cm or q for quit: ').lower()

    if request in 'qQ':
        break
        
    amount, what = request.split() if not request.isdigit() else (request, 'mm')

    # remove plural from known units
    if what[:-1] in units and what[-1] == 's':
        what = what[:-1]           
    elif what[:-2] in units and what[-2:] == 'es':
        what = what[:-2]

    # wrong unit entered
    if what not in units:
        print('Invalid unit: %s' % what)
        print('Units are: %s' % ', '.join(units))
        continue
    
    # list the conversions
    for unit in units:
        print( '%s = %s %s' % ( request, float(amount) * units[what] / units[unit], unit))

Output:

Give amount and unit e.g. 125 cm or q for quit: 3242 parsecs
Invalid unit: parsecs
Units are: inch, mile, ft, cm, mm, m, km

Give amount and unit e.g. 125 cm or q for quit: 123 inches
123 inches = 123.0 inch
123 inches = 0.0194128787879 mile
123 inches = 10.25 ft
123 inches = 3124.2 cm
123 inches = 31242.0 mm
123 inches = 31.242 m
123 inches = 0.031242 km

Give amount and unit e.g. 125 cm or q for quit: 46
46 = 0.181102362205 inch
46 = 2.85830748429e-05 mile
46 = 0.0150918635171 ft
46 = 4.6 cm
46 = 46.0 mm
46 = 0.046 m
46 = 4.6e-05 km

Give amount and unit e.g. 125 cm or q for quit: 123 miles
123 miles = 779328.0 inch
123 miles = 123.0 mile
123 miles = 64944.0 ft
123 miles = 19794931.2 cm
123 miles = 197949312.0 mm
123 miles = 197949.312 m
123 miles = 197.949312 km

Give amount and unit e.g. 125 cm or q for quit: 34 ft
34 ft = 408.0 inch
34 ft = 0.0643939393939 mile
34 ft = 34.0 ft
34 ft = 10363.2 cm
34 ft = 103632.0 mm
34 ft = 103.632 m
34 ft = 0.103632 km

Give amount and unit e.g. 125 cm or q for quit: q
>>>

Edited 4 Years Ago by pyTony: n/a

Hi pyTony great answer. I think you have the values for inches, feet incorrect though. Shouldn't inch be 25.4 and feet should be 304.8. Nice answer though.

Edited 2 Years Ago by LukeKaim: spelling

This article has been dead for over six months. Start a new discussion instead.