float() is a built-in function, so Python comes by default with this ability to convert to float. To use it, we simply write a number or string inside of the parentheses, like this:
float(10)
float(“100”)
You’ll get errors if you try to use it any other way. It cannot be used as below:
Can you? Yes. Would you?, not likely, unless it is in the command line. Python 3 has made this question moot since all evaluations result in a float unless explicitly stated otherwise. No fudging or casting required. Now it’s the other way around for integers.
As I understand it, floor division is the same in both versions. This will need testing…
i tried to use it with a variable like float(cucumbers) and tried to print it, the value inside the cucumber was also a whole number only, this i supposed will turn my data entered in it to as float, but thats not what it did, it returned me just the whole number only.
so can the float function only be used with the numerals and not with the variables,
cucumbers=6
float_cucumbers_per_person=float(cucumbers)/num_people #this worked fine, but not this one
float(cucumbers)
print(cucumbers)
Above we see that the function works fine with either number or variable (assuming a number is at the other end). What we also see is that the shorthand syntax only works on numbers, and not on variables. Just tossing this in.
float(n) doesn’t turn n or the value it refers to, into a float
it creates a float
the only thing float at all does with its argument is to look at it, you get the result as the return value
variables have nothing to do with it, because values are not aware of what is or isn’t referring to them
and values can’t in some way restructure themselves to be something else. If you have a list then that will forever remain a list
if you want to change what a variable refers to, use assignment:
a = float(a)
if the division involves two integers, python will floor (round down) the result. Casting to float after the rounding down will not give the desired output (giving rounding down has already occurred), which is why you cast one of the two numbers to float, so the division involves a float and the rounding down doesn’t occur
Please be careful with your phrasing. “normal” division (/) will always give a float value, but python3 also has floor division (//) which will give an integer. So there are multiple types of division.