Helsman323
Helsman323

Reputation: 21

How to condense a bunch of functions in Python?

So I am trying to make a program to convert units so that I can avoid using factor label method in my physics class. I've figured out the general code for it, but by the end I will have 35 functions to define. Below is the code I have so far, with each unit I would like to be able to convert between on top. Directly below those is each possible conversion using those units. The trouble is I would love to not make functions for each of those possible conversions. The code which I have completed so far is only for a few of those units, but it can be found in a trinket at this link:

             # km  &  m  &  cm  &  mm  &  M  &  ft  &  In 
#km to m   |  m to km  |  cm to km  |  mm to km  |  M to km  |  ft to km  |  In to km
#km to cm  |  m to cm  |  cm to m   |  mm to m   |  M to m   |  ft to m   |  In to m
#km to mm  |  m to mm  |  cm to mm  |  mm to cm  |  M to cm  |  ft to cm  |  In to cm
#km to M   |  m to M   |  cm to M   |  mm to M   |  M to mm  |  ft to mm  |  In to mm
#km to ft  |  m to ft  |  cm to ft  |  mm to ft  |  M to ft  |  ft to M   |  In to M
#km to In  |  m to In  |  cm to In  |  mm to In  |  M to In  |  ft to In  |  In to ft



def km_to_M_conv():
  km=float(input("How many km?"))
  result = km * .621371192
  sentence = '{} km is equal to {} M.'.format(km, result)
  print sentence

def M_to_km_conv():
  M=float(input("How many m?"))
  result = M * 1.60934
  sentence = '{} M is equal to {} km.'.format(M, result)
  print sentence

def km_to_m_conv():
  km=float(input("How many km?"))
  result = km * 1000
  sentence = '{} km is equal to {} m.'.format(km, result)
  print sentence

def mm_to_cm_conv():
  mm=float(input("How many mm?"))
  result = mm * .1
  sentence = '{} mm is equal to {} cm.'.format(mm, result)
  print sentence

def cm_to_mm_conv():
  cm=float(input("How many cm?"))
  result = cm * 10
  sentence = '{} cm  is equal to {} mm.'.format(cm, result)
  print sentence

welcome=input("What would you like to convert?")
if welcome == ("mm to cm"):
  mm_to_cm_conv()
if welcome == ("cm to mm"):
  cm_to_mm_conv()
if welcome == ("km to M"):
  km_to_M_conv()
if welcome == ("M to km"):
  M_to_km_conv()

I'm still fairly new to Python so bear with me. Thanks!

Upvotes: 1

Views: 277

Answers (3)

ZdaR
ZdaR

Reputation: 22964

A better way to approach this problem is probably by creating grouping all your factors against the choices, under a dictionary and then calling the corresponding values of the keys as per the user input. It may be visualised as :

factors = {'mm to cm' : 0.1, 'cm to mm' : 10, 'km to M' : .621371192} # You may like to define more conversion factors here

welcome = input("What would you like to convert?")
frm, _, to = welcome.split()
distance = input("How many "+frm+" ?")

print (str(distance)+frm+' is equal to ' +str(float(distance)*factors[welcome])+ to

Upvotes: 0

or1426
or1426

Reputation: 949

I would pick a standard length (probably metres) and keep a dictionary (if you don't know what a dictionary is then look them up / play with them a bit as they're very useful) stored of how long each unit is in the standard unit. For example:

conversion_factors_dict = {'m': 1,
                           'cm': 0.01,
                           'ft':0.305}

Then your function has to take a number, a "source" unit and a "destination" unit. You first convert the source unit into your standard (metres) and then convert that into your destination unit. For example:

def convert(number, source, destination, conversion_factors_dict):
    input_in_metres = number * conversion_factors_dict[source]
    input_in_destination_units = input_in_metres / conversion_factors_dict[destination]
    return "{}{} = {}{}".format(number, source, input_in_destination_units, destination)

Upvotes: 4

scytale
scytale

Reputation: 12641

factor out common code:

def converter(source, target, factor):
  qty = float(input("How many %s?"))
  result = qty * factor
  print '{} {} is equal to {} {}.'.format(qty, source, result, target)

def km_to_miles(km):
   converter('km', 'miles', 0.621371)

Update:

if you want to be really smart you can dynamically generate the functions like this:

CONVERSIONS = (
    ('km', 'miles', 0.621371),
    ('metres', 'feet', 3.28084),
    ('litres', 'gallons', 0.264172),
)

for from, to, factor in CONVERSIONS:
    func_name = '%s_to_%s' % (from, to)
    func = lambda x: x * factor
    globals()[func_name] = func

    reverse_func_name = '%s_to_%s' % (to, from)
    reverse_func = lambda x: x * (1 / factor)
    globals()[reverse_func_name] = reverse_func

Upvotes: 4

Related Questions