1/2 in python shell gives 0.5 while within a program, it gives 0 -
this question has answer here:
- python division 10 answers
simple question:
when 1/2 in python shell gives float value
>>> 1/2 >>> 0.5 but
sum = 0 in range(1, 20): p = 1/i print(p) val = 2.0**p sum += val print(sum) when run program, value of p comes 0.
what reason behind behaviour. missing?
that's because using python2.7
in python3 1/2 return 0.5
to have same results in python2.7 use this:
from __future__ import division print(1/2) # output 0.5 or suggested @mahi use:
p = 1.0/i
Comments
Post a Comment