Division in Python 2.7. and 3.3

How can I separate two numbers in Python 2.7 and get the result with decimal places?

I do not understand why there is a difference:

in Python 3:

>>> 20/15 1.3333333333333333 

in Python 2:

 >>> 20/15 1 

Isn't that modulo?

+60
python division
Jan 23 '14 at 18:54
source share
4 answers

In python 2.7, the / operator is an integer division if the input is integers.

If you want to split the floats (which I always prefer), just use this special import:

 from __future__ import division 

See it here:

 >>> 7 / 2 3 >>> from __future__ import division >>> 7 / 2 3.5 >>> 

Integer division is achieved using // , and modulo using %

 >>> 7 % 2 1 >>> 7 // 2 3 >>> 

EDIT

As user2357112 commented, this import must be done before any other regular import.

+99
Jan 23 '14 at 19:01
source share

In Python 3, / - float division

In Python 2 / - integer division (assuming int entered)

In both cases 2 and 3, // is a whole division

(To obtain a float division in Python 2, any of the operands must be a float, either as 20. or float(20) )

+40
Jan 23 '14 at 18:56
source share

In Python 2.x, make sure you have at least one operand of your division in the float . There are several ways to do this:

 20. / 15 20 / float(15) 
+14
Jan 23 '14 at 19:00
source share

"/" is an integer division in python 2, so it will be rounded to an integer. If you want to return the decimal place, just change the type of one of the inputs to float:

float(20)/15 #1.33333333

+9
Jan 23 '14 at 19:02
source share



All Articles