I can not get floats return by expressions

3

When I try to give print(6/10) I get a int (0) instead of a float (0.6)

And if I give type(6/10) it returns int .

I'm following this tutorial and doing exactly the same steps both in pyCharm and in IDLE, however it can get 'float' results and I do not.

    
asked by anonymous 27.02.2015 / 08:31

2 answers

4

The problem is that you are using Python 2.7. I do not recommend using it, prefer to use version 3.0 onwards. Firstly because you are following a tutorial using this version, second because there are no gains in using an older version unless you have legacy code, which is not the case.

There is really this difference in behavior. Python 2.7 had these "problems" that were obviously fixed in the latest version to follow the Python philosophy and not use the philosophy of another language as it did before.

DeviaSerFloat = 6/10 #inteiro ou flutuante dependendo da implementação
EhFloat = 6.0/10.0 #força ponto flutuante
EhInt = 6//10 #força inteiro
print(DeviaSerFloat)
print(EhFloat)
print(EhInt)

See Python 2.7 running on ideone .

Now see the Python 3.0 running on ideone .

    
27.02.2015 / 08:59
4

This is due to a change in the semantics of the division between Python versions 2.X and 3.X.

In Python 2.X operations between integers always return an integer, so 6/10 is interpreted as the integer division - and therefore rounded to zero. It is necessary to convert one of the operands to float to do the floating-point division: 6.0/10 or 6/10.0 . This behavior has been "inherited" from C-like languages.

In Python 3.X, the division between integers can return a floating point. To make an integer division in this version it is necessary to use another operator: 6//10 . This behavior is more common in modern languages, especially dynamic typing.

The integer division operator also works on Python 2.X - and it returns an integer even when its operands are floats: 6.0 // 10.0 will give zero. Since the common division operator (called "true division") maintains the default behavior of its version for compatibility, but if you want to use the new semantics in Python 2.X simply do the following < in> import :

from __future__ import division

From there, the split will work as in 3.X (if this needs to be done in each source file or not, I'm not sure, I'd have to test or reference some reference).

Font

    
27.02.2015 / 09:48