How to use the float function in Python?
In Python, the float() function is used to convert other data types into floating-point numbers. For example, you can convert integers into floating-point numbers, as well as convert numbers represented as strings into floating-point numbers.
Here are some examples of how it can be used:
- Convert integers to floating-point numbers.
num = 10
float_num = float(num)
print(float_num)
- Convert a string to a floating point number.
str_num = "3.14"
float_num = float(str_num)
print(float_num)
- Incorrect value
str_num = "abc"
try:
float_num = float(str_num)
except ValueError:
print("Invalid float value")
It is important to note that the float() function automatically removes leading and trailing spaces when converting a string.