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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With