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
>>>
Comments
-
Avraam Mavridis over 1 year
I am new to Python and I started studying the basics. I am a C++ guy so the // operator was something new. According with a book that I am reading:
>> 4/2 2.0 >> 2/4 0.5 >> 5//4 2 >> 2//4 0
The problem is that when I write
5//4
the result is 1,when I write4/2
the result is 2 and not 2.0 and when I write2/4
the result is 0 . I have to write `2.0/4.0' to have 0.5 as the result. Is these author's mistakes or am I doing something wrong?I am using Python 2.7.4, [GCC 4.7.3] on linux2