Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division in Python 2.7. and 3.3 [duplicate]

How can I divide two numbers in Python 2.7 and get the result with decimals?

I don't get it why there is difference:

in Python 3:

>>> 20/15 1.3333333333333333 

in Python 2:

>>> 20/15 1 

Isn't this a modulo actually?

like image 271
Erzsebet Avatar asked Jan 23 '14 18:01

Erzsebet


People also ask

How do you divide two variables in Python?

Python Integer Division To perform integer division in Python, you can use // operator. // operator accepts two arguments and performs integer division. A simple example would be result = a//b . In the following example program, we shall take two variables and perform integer division using // operator.

How do you use division in Python?

In Python, there are two types of division operators: / : Divides the number on its left by the number on its right and returns a floating point value. // : Divides the number on its left by the number on its right, rounds down the answer, and returns a whole number.

What are the two types of division in Python?

Python has two division operators, a single slash character for classic division and a double-slash for “floor” division (rounds down to nearest whole number). Classic division means that if the operands are both integers, it will perform floor division, while for floating point numbers, it represents true division.

How do you float a division in Python?

To divide float values in Python, use the / operator. The Division operator / takes two parameters and returns the float division. Float division produces a floating-point conjecture of the result of a division. If you are working with Python 3 and you need to perform a float division, then use the division operator.


1 Answers

In Python 2.7, the / operator is integer division if inputs are integers.

If you want float division (which is something 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 by using //, and modulo by using %:

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

As commented by user2357112, this import has to be done before any other normal import.

like image 118
bgusach Avatar answered Oct 14 '22 11:10

bgusach