print(float()) # 0.0
print(float(5)) # 5.0
print(float("34.5")) # 34.5
print(float(" 45.8 ")) # 45.8
print(float("InF")) # inf
print(float("NaN")) #nan
print(float("Infinity"))#inf
We will get error message based on input
print(float('abc45'))
Output
ValueError: could not convert string to float: 'abc45'
print(type(4.5)) # <class 'float'>
Use try-except to handle cases where the input is not a valid float:
try:
print(float('abc'))
except ValueError:
print("Invalid input for float conversion")
In web forms or data input systems, user input is often received as a string. You can use float() to safely convert this data into a usable floating-point number:
user_input = "45.67"
converted_value = float(user_input)
print(converted_value) # Output: 45.67
The float() function can handle special values like inf and NaN:
print(float('NaN')) # Output: nan
print(float('Inf')) # Output: inf
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.