Oct-26-2020, 09:36 PM
(This post was last modified: Oct-27-2020, 09:26 PM by deanhystad.)
I wouldn't understand why 10/3 == 3 either. I cannot find a way to make 10/3 == 3. But I cannot do that because I am running Python 3.8. If I was running Python 2.7 10/3 does == 3.
In Python pre 3, dividing an integer by an integer produced an integer. That is why 10 / 3 == 3. It cannot equal 3.33333 because 3.3333 is not an integer. 3 the integer part left over when you remove the fractional .333333 part, so the answer is 3.
To do the same trick in Python 3 you need to add extra code. int(10/3) == 3.
By the way, integer division in C or C++ works the same way.
Things change when you start using floats. A float divided by anything produces a float and dividing anything by a float produces a float. That is why 10.0 / 3.0 == 3.333333 and 10.0 / 3 == 3.3333 and 10 / 3.0 == 3.33333. In this Python 2 and Python 3 agree. When you do math operations, if any of the operands is a float the result is a float.
By the way, floating point division in C or C++ works the same way.
There is a misconception that "//" is integer division in Python 3. This is incorrect. "//" is "floor division". Floor division is similar to integer division, but the result is not necessarily an integer.
10 // 3 == 3, 3 is an integer
10.0 // 3.0 == 3.0, 3.0 is a float if dividend or divisor are floats.
In Python pre 3, dividing an integer by an integer produced an integer. That is why 10 / 3 == 3. It cannot equal 3.33333 because 3.3333 is not an integer. 3 the integer part left over when you remove the fractional .333333 part, so the answer is 3.
To do the same trick in Python 3 you need to add extra code. int(10/3) == 3.
By the way, integer division in C or C++ works the same way.
Things change when you start using floats. A float divided by anything produces a float and dividing anything by a float produces a float. That is why 10.0 / 3.0 == 3.333333 and 10.0 / 3 == 3.3333 and 10 / 3.0 == 3.33333. In this Python 2 and Python 3 agree. When you do math operations, if any of the operands is a float the result is a float.
By the way, floating point division in C or C++ works the same way.
There is a misconception that "//" is integer division in Python 3. This is incorrect. "//" is "floor division". Floor division is similar to integer division, but the result is not necessarily an integer.
10 // 3 == 3, 3 is an integer
10.0 // 3.0 == 3.0, 3.0 is a float if dividend or divisor are floats.