+ 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.
7 odpowiedzi
+ 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
+ 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.
+ 3
Yes, as soon as one of numbers here is float the result will ne float.
+ 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
+ 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
+ 1
That's understandable.
But...
Lesson 4.1., last question.
If you choose integer as an answer, it says:Try again.
+ 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.