Number divided by a divisor greater than it returns zero?

Asked

Viewed 1,109 times

3

I went to do a calculation on Python 2.7 and got scared when I saw the result:

 val = 1 / 16
 print(val); # 0

Example in IDEONE

That is, when we make a division where the divided number is less than the divisor, the returned result is zero.

  • How do I get the result in float?

  • Why does Python behave this way?

  • 2

    In Python 3 this changed. From what I read about this change, it was precisely because it made the understanding confusing. Now, in Python 3, the entire division is another operator: val = 1 // 16; the two bars // represent the entire division

2 answers

8


Integer division, returns integer. Make one of them to be of the type float:

val = float(1) / 16
print(val);

#saida: 0.0625

Or it forces the change in the behavior of the operator / to be the same as python3.x:

from __future__ import division

val = 1/16
print(val);

#saida: 0.0625
  • 1

    Integer division, returns integer.... PHP and Javascript are exception :p

  • 1

    @Wallacemaxters Now laugh seriously.

  • 1

    In fact, this behavior is disconcerting in a dynamic typing language like Python. So much so that they tidied up in Python 3 - but it’s one of the only cases where Python automatically does type conversion.

5

  • 3

    It’s not the rule in dynamic typing languages. And, would be worth mentioning that the behavior has changed in Python 3. For those who still need to use Python 2, force the behavior with fewer surprises with from __future__ import division It’s better than worrying about explicit conversion in every room. (Python has dynamic but strong typing - the split, in Python 3, has become the exception confirming the rule)

  • This has nothing to do with whether the language is dynamic or not, whether it has strong typing or not. When a language means strong typing, it should do it. When you do the right thing initially and then decide to go the wrong way, you lack direction. Each can do what they think best, but operation with one type should not generate another type unless the language declares itself weak.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.