Вопрос

Why is this function printing a float if the "//" applies to integers?

>>> minimum = int((a + b) - math.fabs(a-b))//2      
>>> print(type(minimum))
Это было полезно?

Решение

// doesn't means will return integer, operator // is called (floor division), but may return float or int it depends on operand type e.g: 9//2 is equal to 4 and 9.0//2.0 is equal to 4.0. that is float.

5.6. Binary arithmetic operations¶

The / (division) and // (floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type. Plain or long integer division yields an integer of the same type; "the result is that of mathematical division with the ‘floor’ function applied to the result". Division by zero raises the ZeroDivisionError exception.

Check ideone's link of working example for Python3._:
Following example will may be helpful to understand difference between / and // and why // useful (read comments):

a = 9.0
b = 2.0

print a//b   # floor division gives `4.0` instead of `4.5` 

a = 9
b = 2

print a/b   # int division because both `b` and `a` are `int` => `4.5`  
print a//b  # float division returns `4`

a = 9.0
b = 2

print a/b   # float division gives `4.5` because `a` is a float  
print a//b  # floor division fives `4.0`

Output:

4.0   # you doubt 
4.5   
4 
4.5   # usefulness of //
4.0

Now in your expression both operands are int so answer is int type:

  int((a + b) - math.fabs(a-b))  //  2 
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^     ^^      
#   int due to casting              int   => `minimum` as int    

So // can result float if any operand is a float but magnitude is equals to floor.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top