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
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.