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

cm-to-inch calculator

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

Problem

After a few pages reading Learning Python Hard Way, I've decided to try to make a simple cm-to-inch calculator. I am very excited about this achievement, and I want someone to check my code. It works well, but i just need someone to confirm everything is written well.

# cm to inch calculator
inch = 2.54 #centimeters
centimeters = int(input("Enter a number of centimeters"))
print "Entered number of %s centimeters is equal to %s inches" % (centimeters , centimeters / inch)

Solution

Great work so far! And good on you for seeking review. In general, your code is pretty good, and works correctly. As you've asked, though, here are some suggestions for improvement.

The assignment:

inch = 2.54 #centimeters


is potentially confusing; instead, you could make it clear that it is a ratio:

CM_PER_INCH = 2.54


Note the UPPERCASE_WITH_UNDERSCORES name for a constant, per the style guide.

centimeters = int(input("Enter a number of centimeters"))


There is no reason to limit the user to int input - why not allow float? Then they can enter and convert e.g. 4.2cm.

Also, this will fail with input that can't be converted to an integer (what if the user types seven?) - have a look at this SO community wiki if you want to add validation.

print "Entered number of %s centimeters is equal to %s inches" % (centimeters , centimeters / inch)


This line is too long (see the style guide again). Also, % formatting is a little old-fashioned, compared to str.format. I would split this into two lines:

template = '{.2f}cm is equal to {.2f}"'
print template.format(centimeters, centimeters / CM_PER_INCH)


Or use line continuation:

print '{.2f}cm is equal to {.2f}"'.format(
    centimeters,
    centimeters / CM_PER_INCH
)


In use:

>>> print template.format(float(centimeters), centimeters / CM_PER_INCH)
5.00cm is equal to 1.97"


If you want another challenge, have a go at implementing the reverse calculation, and allowing the user to choose which way to convert.

Code Snippets

inch = 2.54 #centimeters
CM_PER_INCH = 2.54
centimeters = int(input("Enter a number of centimeters"))
print "Entered number of %s centimeters is equal to %s inches" % (centimeters , centimeters / inch)
template = '{.2f}cm is equal to {.2f}"'
print template.format(centimeters, centimeters / CM_PER_INCH)

Context

StackExchange Code Review Q#80616, answer score: 20

Revisions (0)

No revisions yet.