9

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?

2
  • Are you saying that the tutorial didn't make the requirement for a decimal point clear enough? Commented Dec 13, 2010 at 19:18
  • yes, That's why the tutorial is called "Learn Python The Hard Way" :P Commented Feb 7, 2014 at 14:48

7 Answers 7

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm doing this example right now, this answered my question, thanks!
5

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 

Comments

2

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.

Comments

1

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'> 

Comments

1

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

Comments

0

Any number with a decimal is a floating point number.

In python take the following example,

If you divide 11/4 the output will be 2 [here 11 is not a floating point number]

But if you divide 11.0/4, the output will be 2.75 [here 11.0 is a floating point number].

Here's a screenshot

Comments

0

python console print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) I get 7 but in pycharm I get 6.75.

1 Comment

Python 2 will give you 7. Python 3 will give you 6.75. Try 7 / 2 in both version of Python to see the difference.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.