Your code looks ok and probably does the job properly :-)
However, it is not quite perfect. Python has a code style called PEP8 and is definitly worth a read. Among other things, it says :
Constants Constants are usually defined on a module level and written
in all capital letters with underscores separating words. Examples
include MAX_OVERFLOW and TOTAL .
inch definitly looks like a constant so
INCH would be better.
Also, not really important but you have an "extraneous whitespace" in
(centimeters , centimeters.
Also, instead of having your conversion logic hidden in your logic handling input/output (with
print), you might want to extract in in a simple function.
Another to know if you are beginning with Python is that a good thing to do is to have your definitions of constants/functions/classes/etc in a file in such a way that you can re-use it later on (via imports mechanisms). If you don't want your logic "actually doing something" to mess with everything when you import your code, the technic is to use an
if __name__ == "__main__": guard.
Naming is quite important in programming. Here
centimeters in top of being long does not convey much meaning. I reckon
nb_cm gives more information. Similarly,
NB_CM_IN_INCH is better than
It could be a good idea to handle
float values on top of integers.
Python 3 (and notes about
Final thing before I forget, from the way you have used
print, I guess you are using Python 2. If you have no special reason to do so, you might want to start using Python 3 instead. You'll find a few things slightly different but you'll be better off learning directly on the latest versions so you have the good habits and nothing to un-learn.
However, I have to point out that
input is "slightly" different on the 2 versions of Python.
input from Python 3 corresponds to
input from Python 2 can be simulated in Python 3 with
Indeed, as you might or might not know, what you were doing is doing more that merely asking a string from the user, it was asking for Python code and handling it as such.
Enter a number of centimeters 2*3
Entered number of 6 centimeters is equal to 2.36220472441 inches
See how the number was evaluated. It looks good in theory or in you really know what you are doing. In most cases, using
eval directly or indirectly is considered a bad practice.
Here's my version of the code (works in Python 2 but behavior is slightly different - cf note above).
NB_CM_IN_INCH = 2.54
"""You can put docstrings here :)."""
return val / NB_CM_IN_INCH
"""And here :D."""
return val * NB_CM_IN_INCH
if __name__ == "__main__":
nb_cm = float(input("Enter a number of centimeters: "))
print("Entered number of %s centimeters is equal to %s inches" % (nb_cm, convert_cm_in_inch(nb_cm)))
It seems like I have said many things so I want you not to take it as criticism of your good but as advices if you keep on programming in Python.