views:

120

answers:

1

I'm a very early-stage python programmer, and I wrote this simple script to convert miles to kilometers or kilometers to miles:

metrics_dict = {("miles", "kilometers"):1.609344, ("kilometers","miles"):0.62137119}

number = float(raw_input("Enter the number of units you would like to convert: "))

from_metric = raw_input("I would like to convert from (miles or kilomters): ")

to_metric = raw_input("to(miles or kilomters): ")

conversion = metrics_dict.get((from_metric,to_metric), "You messed up somewhere!")

def convert_func():

    answer = number * conversion
    print number , from_metric, "is equal to", answer , to_metric 

convert_func()

I'm sure this code is ugly. How could I better structure it?

Also, how do I run the entire thing? It only works if I run each line separately in IDLE.

+5  A: 

To run the entire thing, save it as a file with the .py extension (not strictly necessary but conventional) then, from a console/terminal window (windows key + c on windows, you'll know on Linux) type

python yourfilename.py

and it'll run.

There is nothing ostensibly wrong with what you've done, or ugly for that matter. What you might want to think about for future reference is being general: how can I write this code so I can re-use most of it? For example, your conversion_func() relies on existing parameters in the file-scope. You could re-write it:

def conversion(number, conversion)
    return number*conversion

To use this, you do (replace x and y):

answer = conversion(number=x, conversion=y)

That way, if you wanted to do this conversion in the middle of some other process it would be much easier to do using existing code. You can still print the result to the user.

Of course, this is a relatively simple example. You will definitely come across times when re-using the same idea will save you a lot of time.


You could also do the same thing with the user input functions, like so:

def getuserinput():
    input = dict()
    input["number"] = float(raw_input("Enter the number of units you would like to convert: "))
    input["from_metric"] = raw_input("I would like to convert from (miles or kilomters): ")
    input["to_metric"] = raw_input("to(miles or kilomters): ")

    return input

Then you can do:

input = getuserinput()

and then anywhere you need to read these parameters, do input["parametername"].

Ninefingers
Thanks! How can you control for the fact that someone may enter miles twice? or may misspell kilometers?Maybe a try/except statement?
Justin Meltzer
That would do it - of the top of my head requesting a dictionary element that does not exist throws a KeyError exception, so if it can't find the key it would do exactly that. If you wanted more detailed feedback, you then look at what the pair of values actually are, for example `if input["from_metric"] == input["to_metric"]:` if this statement holds true, the two are the same and you can print "you entered the same thing twice!".
Ninefingers