Python Forum
Integer vs Floats - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Integer vs Floats (/thread-15233.html)



Integer vs Floats - Tazbo - Jan-09-2019

Hi,

I am currently learning Python from an online course and today is my first day. I am a little confused on Integers when dividing instead of adding.

If I write


 print ((1 + 2) + 5) 
I get the answer 8 as an Integer but If I write
 print ((1 + 2) * 5 / 3) 
I get 5.0 instead of 5, why does the output give me an float instead of an Integer when I divide?

Thanks


RE: Integer vs Floats - micseydel - Jan-09-2019

In most programming languages (Python 2 included), dividing two integers results in "integer division" which mean that the floating point part is just discarded and you end up with an integer. In Python 3, division works as you would expect. Further, any computations that involve a floating point number will result in a floating point number. In theory Python could give you an integer, since your floating point number is an integer, but it doesn't.


RE: Integer vs Floats - Gribouillis - Jan-09-2019

Use // instead of / to get an integer.