The float() function in Python is used to convert a string or a number to a floating-point number. It takes a single argument, which can be a string, an integer, or a floating-point number.
Here are some examples of how to use the float() function:
# Convert a string to a floatfloat_num = float("3.14")print(float_num) # Output: 3.14# Convert an integer to a floatfloat_num = float(5)print(float_num) # Output: 5.0# Convert a floating-point number to a float (no change)float_num = float(3.14)print(float_num) # Output: 3.14 |
In the first example, the float() function is used to convert the string "3.14" to a floating-point number. The resulting value is assigned to the variable float_num, which is then printed to the console.
In the second example, the float() function is used to convert the integer 5 to a floating-point number. Since the integer 5 has no decimal places, the resulting value is 5.0.
In the third example, the float() function is used to convert the floating-point number 3.14 to a floating-point number. Since the input is already a floating-point number, the output is the same as the input.
It is important to note that the float() function can raise a ValueError exception if the input argument cannot be converted to a floating-point number. For example, if you pass a string that contains non-numeric characters, the float() function will raise a ValueError exception. Therefore, it is a good practice to always use error handling when working with the float() function.