cm-to-inch calculator 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)
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:

&gt;&gt;&gt; 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.