Ad

Number Output Sometime Have .0

- 1 answer

Code:

n = 18
total = 0
while n <=35:
 total += (n/2)
 print(total)
 n += 2 

Output:`

9.0
19.0
30.0
42.0
55.0
69.0
84.0
100.0
117.0`

Second code:

n = 40
total = 2
while n >=25:
 total += n
 print(total)
 n -= 3 `

Output:

42
79
113
144
172
197

Question: Why is the first output have .0 behind the integer while second output does not have although 2 codes look similar

Ad

Answer

In Python 3, dividing two integers with the / operator produces float values, for example

>>> 1/2
0.5

... but also

>>> 1/1
1.0

(In Python 2, you would get 0 and 1!)

In the first iteration, you are adding an int and float with total += (n/2) and two floats in subsequent iterations. Both of these additions produce float values.

The trailing .0 only looks weird because you exclusively compute values that could be expressed as integers.

Having int_a/int_b become a float (in Python 3), even when the result could be written as an integer, is just consistent.

It would be weird if dividing some integers would produce float values and divinding some other integers would produce int values.

In your second code snippet, you only add and substract integers from each other, which produces int values, so you don't see a trailing .0.

Finally, if you want to enforce integer division, use the // operator.

>>> 1//2
0
>>> 1//1
1

// in Python 3 behaves like / did in Python 2.

Ad
source: stackoverflow.com
Ad