So, I open terminal.
> python
> 1 / 3
0
> 1.0 / 3
0.33333333333333331
Could someone tell me what the rules are when it comes to decimals. Does it matter which number when being divided carries the decimal? Is there a best practice?
If I want more decimal points, or less for that matter, do I need to use a function?
The division in Python < 3.0 works like in many different programming languages and the output is an integer:
>>> 3 / 2
1
If you use float for any of the parts, the output will be a float also:
>>> 3.0 / 2
1.5
>>> 3 / 2.0
1.5
But there is a solution, if you want to do division more precisely without the need to convert some of the parts into float:
>>> from __future__ import division
>>> 3 / 2
1.5
After the above you can still make "classical divisions" by using double slashes:
>>> 3 // 2
1
Is it clear enough? Did it help?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With