How does float( ) work?


#1

Question

How does float() turn my number into a float?

Answer

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:

10.float()            # invalid
float() = my_integer  # invalid

To see a list of all built-in functions available in Python 2, take a look at this documentation page!


FAQ: Learn Python - Python Syntax - Two Types of Division
#2

9 posts were split to a new topic: Cucmber logic


#10

Ah. Okay, thank you. That explains it.


#11

Can i write float like this
Variable name = float(100.)/6 if not can u guys explain me how should i. correct this


#12

100. is a float, converting that to float would be super-unnecessary
Nobody but you can correct that, because only you know what you meant by it.


#13

Can i write float like this
float_cucumbers_per_person = cucumbers ./num_people
if not can you guys please explain that for me? thanks


#14

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…

1 // 1    =>  1
1.0 // 1  =>  1.0
1 // 1.0  =>  1.0