Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's / and // operators on 2.7.4

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 write 4/2 the result is 2 and not 2.0 and when I write 2/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

like image 250
Avraam Mavridis Avatar asked Jan 13 '23 03:01

Avraam Mavridis


2 Answers

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
like image 50
Dhara Avatar answered Jan 15 '23 19:01

Dhara


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
>>> 
like image 30
Deepu Avatar answered Jan 15 '23 18:01

Deepu