Floating Point in Python
Solution 1
For floating point numbers you write a period after the number, and a zero (if it's a whole number).
Like this:
1.0 <---- Floating point.
1 <------- integer
That is how python interprets them.
if my_answer != your_question:
print "I did not understand your question. Please rephrase it."
else:
print "Good luck. Python is fun."
I agree with rohit, the 0 is not needed. Although it makes things easier for beginners.
Solution 2
Passing a value to the float()
constructor will make it a float
if possible.
print float(2)
print float('4.5')
Use string interpolation or formatting to display them.
print '%.3f' % 4.53
Solution 3
3 is an integer.
3.0 is a float.
>>> type(3)
<type 'int'>
>>> type(3.0)
<type 'float'>
round():
Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number.
So that is why in your case, 6.0 is returned.
Solution 4
Orange, read the last question in the lesson, the author gave you the answer
Why does / (divide) round down? It's not really rounding down; it's just dropping the fractional part after the decimal. Try doing 7.0 / 4.0 and compare it to 7 / 4 and you'll see the difference.
good luck
Solution 5
Agree with all of the answers above. You don't even need to put a zero after the period though.
For example:
In [1]: type(3)
Out[1]: <type 'int'>
In [2]: type(3.)
Out[2]: <type 'float'>
orange
Updated on July 26, 2022Comments
-
orange almost 2 years
I'm learning via Learn Python The Hard Way and I've come across:
Notice the math seems “wrong”? There are no fractions, only whole numbers. Find out why by researching what a “floating point” number is.
I've read what it is on: http://docs.python.org/tutorial/floatingpoint.html
I can't figure out on how I can output floating point numbers, I've thought about using
round(3 + 3, 2)
.Is this right?
-
Drewdin over 11 yearsI'm doing this example right now, this answered my question, thanks!
-
R891 over 6 yearsPython 2 will give you 7. Python 3 will give you 6.75. Try
7 / 2
in both version of Python to see the difference.