+ 3

Calculation output - integer or float

Sometimes Python gives integer as an output of calculation and sometimes a float. What makes a difference? The reason I ask are some exercises on Sololearn.

10th Jun 2022, 5:20 PM
Hisham H
Hisham H - avatar
7 Respuestas
+ 5
It depends on your calculation but this comes to my mind: using floor division: // returns an integer (rounded down to the nearest integer) using float division: / returns a float e.g. 5//2 = 2 5/2 = 2.5
10th Jun 2022, 5:45 PM
Denise Roßberg
Denise Roßberg - avatar
+ 4
EuroMuslim I would say this is true for all operators: as soon as a number is a float, a float is returned. 5.0/2 -> 2.5 5.0//2 -> 2.0 5.0*2 -> 10.0 and so on... You can try it out in the playground.
10th Jun 2022, 6:16 PM
Denise Roßberg
Denise Roßberg - avatar
+ 3
Yes, as soon as one of numbers here is float the result will ne float.
10th Jun 2022, 6:08 PM
Hisham H
Hisham H - avatar
+ 3
EuroMuslim also if the result of division of two integers has a reminder the result will be a float. As Denise Roßberg mentioned at the outset 5/2 -> 2.5 5//2 -> 2
10th Jun 2022, 7:26 PM
Paul K Sadler
Paul K Sadler - avatar
+ 2
One more subtle point is that floor division // returns integer only if both operands are integer. 5//2 = 2 5.//2 = 2.0 5//2. = 2.0
10th Jun 2022, 11:42 PM
Brian
Brian - avatar
+ 1
That's understandable. But... Lesson 4.1., last question. If you choose integer as an answer, it says:Try again.
10th Jun 2022, 5:58 PM
Hisham H
Hisham H - avatar
+ 1
You mean this one? print(1+2+3+4.0+5) In this case you adding integers to a float, so the result will be a float.
10th Jun 2022, 6:04 PM
Denise Roßberg
Denise Roßberg - avatar