The call type (1/2) returns an integer?

So, I noticed that the call:

print type(1/2) 

returns an integer, however should it not be a float?

+5
source share
2 answers

Try type(1/2.0) , this will return a float. One of the numbers must be a float to get the return value in a float.

The Python-2.x split operator follows the classic division. When representing integer operands, classical division truncates the decimal place, returning an integer (also known as gender division). If a pair of floating point operands is specified, it returns the actual floating point quotient (otherwise, this is a true division).

Example:

 >>> 1 / 2 # integer truncation (floor division) 0 >>> 1.0 / 2.0 # returns real quotient (true division) 0.5 

In Python 3.x, division works differently. type(1/2) will return a float type. The Python-3.x separation operator follows True Division.

+7
source

In Python 2x, a section without remainder/divider added to quotient => sex separation If you want to force 2x to return true division ( remainder/divider added to private), try.

 >>>from __future__ import division >>>2/3 >>>0.6666666666666666 

But if you need to revert to the previous behavior (i.e. gender separation), try

 >>>2//3 >>>0 

In Python 3x, true division occurs -

0
source

Source: https://habr.com/ru/post/1236306/


All Articles