Python's / And // Operators On 2.7.4
Solution 1:
In Python 2.x, the default division operator is "Classic division". This means that /
, when used with integer operators will result in integer division similar to C++ or java [i.e. 4/3 = 1
].
In Python 3.x, this is changed. There, /
refers to "True division" [4/3 = 1.3333..
], whereas //
is used to request "Classic/Floor division".
If you want enable "True division" in Python 2.7, you can use from __future__ import division
in your code.
Source: PEP 238
For example:
>>> 4/3
1
>>> 4//3
1
>>> from __future__ import division
>>> 4/3
1.3333333333333333
>>> 4//3
1
Solution 2:
The difference occurs in case of Python 3.x
.
In Python 3.0, 7 / 2
will return 3.5 and 7 // 2
will return 3. The operator /
is floating point division
, and the operator //
is floor division
or integer division
.
But in case of Python 2.x
there won't be any difference and the text is wrong I believe, here is the output I am getting.
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on
win32
Type "copyright", "credits" or "license()" for more information.
>>> 4/2
2
>>> 2/4
0
>>> 5//4
1
>>> 2//4
0
>>>
Solution 3:
The //
seems to be working correctly,
See this tutorial on operators.
// = Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. 9//2 is equal to 4 and 9.0//2.0 is equal to 4.0
for 4/2
to equal 2.0
you need to specify a float. For example : 4/float(2)
evaluates to 2.0
. The ints 4
and 2
are not already defined as floats
when you divide.
Hope it helps!
Solution 4:
In python 2.7 and prior, there always integer division unless there is a float. Both / and // are integer division in python 2.7 and prior.
>>>4/3
1
>>>4//3
1
>>>4/2.0
2.0
>>> 4//1.5
2.0
In python 3.2 and later / is for float division and // for integer division
>>>4/2
2
>>>4/2.0
2.0
>>>3/2
1.5
So in python 2.7 if you want to return an accurate float number,the divisor or the divider must be float,else you will get an integer division no matter what symbol you use for division / or //.If you use a float with the // you will get an integer with .0 at the end.
In python 3.2++ if you want an integer division you use //,if you want floating division you use /.
see this for the differences between python versions.
Post a Comment for "Python's / And // Operators On 2.7.4"