Python

[Python] Differences in division Python2 and Python3

Darane 2021. 9. 3. 15:16

 

There is a difference in division result when integer data is divided by Python2 and Python3 versions.

 

In the Python2 version, dividing integers results in integer data, and in the Python3 version, dividing integers results in float data.

 

Since the data type of integer division differs according to the version difference, if the source is implemented without considering the version-specific difference, a logical error may occur. The result of the program may be different from the intention.

 

Python2

You can see that the result of division is an integer(1), and if you look at the type of the division result using the type() function, you can see that it is of type 'int'.

print(6 / 5) 
print(type(6 / 5)) 

#Result 
1 
<type 'int'>

 

 

Python3

You can see that the division result is a real number(1.2) and the type is a 'float' type

print(6 / 5) 
print(type(6 / 5)) 

#Result 
1.2 
<class 'float'>

 

반응형

 

The result of integer and float division does not differ by version.

Python2

print(6 / 5.0) 
print(type(6 / 5.0)) 

#Result 
1.2 
<type 'float'>

 

Python3

print(6 / 5.0) 
print(type(6 / 5.0)) 

#Result 
1.2 
<class 'float'>

 

from __future__ import division

If you want to get the result of integer division in Python2 as float(real) data as in Python3, import the module as in the example below.

from __future__ import division 

print(6 / 5) 
print(type(6 / 5)) 

#Result 
1.2 
<class 'float'>

 

반응형