I have been trying to make a height calculator that converts cm to feet, here is my code:
print "how tall are you (in cm)?"
cm = raw_input()
answer = cm*int(0.03280839)
print answer
I know it's pretty simple but I have only just started so any tips on what is wrong would be great. Thanks in advance.
cm is a string. You need to convert it to an number (integer or float) first. (You don't want to convert your conversion factor to an integer, since the result would just be multiplying the height by 0.)
print "how tall are you (in cm)?"
cm = raw_input()
answer = int(cm)*0.03280839
print answer
This just might be me, but 0.03280839 didn't strike me as an obvious conversion factor, while 2.54 (cm/inches) was much more recognizable. You can let Python do the work of converting cm to feet for you--convert to inches first, then convert to fee--for more readable code:
answer = int(cm) * 2.54 / 12
Or better yet, define a constant to use in place of the "magic" number.
FEET_PER_CM = 2.54 / 12 # 2.54 cm/inch ÷ 12 in/foot
# ...
answer = int(cm) * FEET_PER_CM
Firstly, when you use raw_input(), it would return you a string. So you have to convert it to integer using int(cm)
Secondly, int(0.03280839) would round the number and return 0. Why are you using int on that? just cut down the int from there. So the finished code should be:
print "how tall are you (in cm)?"
cm = raw_input()
answer = int(cm) * 0.03280839 # use int(cm) to convert the string to integer
print answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With