HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Inch <-> cm conversion program

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
conversionprograminch

Problem

I just wrote this small inch cm conversion program. It works just fine, although I know that I've done some things in a rather stupid manner and that it could be improved.

def conversion():
    try: amount = int(raw_input("Please enter the value: "))
    except ValueError:
        print "Please specify a valid amount."
        return conversion()
    answer = raw_input("Please choose between converting FROM kilograms/pounds: ")
    if answer == "kilograms":
        return amount * 2.2
    elif answer == "pounds":
        return amount / 1.45
    else:
        print "Please choose between kilograms and pounds."
        restart = raw_input("Try again? ")
        if restart == "yes":
            return conversion()
        elif restart == "y":
            return conversion()
        else:
            print "Okay, bye."
            return

print conversion()

Solution

The first point would be the separation of concerns: every entity (function, class …) should only be responsible for one task (except, ironically, printing the result).

In your code, one function (conversion) is responsible for everything. Try separating the different issues:

  • user input



  • conversion



  • output



Granted, for such a very small program the result will almost certainly be larger. But it will also be much clearer and easier to extend.

Next up, your use of recursion. I love recursion as much (more!) as the next programmer but in your case a few loops wouldn’t hurt readability.

A third point, magic constants should be avoided. Your use of the conversion factors 2.2 and 1.45 is innocuous enough but it soon becomes a problem in larger programs. Use properly-named constants instead.

Context

StackExchange Code Review Q#1952, answer score: 6

Revisions (0)

No revisions yet.