Steps to check if a value can be converted to float or not:
- Pass the value to the
float()
method and wrap it inside atry/except
block. - If the
try
block run successfully, it indicates that the value is convertible to float. - If the
except
block is executed, it indicates that the value cannot be converted to float.
If we run the above code, we will get the message "Value is convertible to float" since the passed value "3.14" is in fact a float.
Let's try passing a non-float value to raise a "ValueError" in except
block.
value = 'sharooq'
try:
result = float(value)
print("Value is convertible to float")
except ValueError:
print('Value is not convertible to float')
This code will trigger the except block and print the message "Value is not convertible to float".
With this logic, it is possible to create a function which can be reused. Refer to the following code for the reusable function:
Running the above code will result in the following output:
We defined a function called "convertable_to_float" to check whether a value is convertible to float or not. The function will return "true" if it is convertible and returns "false" if it is non-converible.
If you found this article useful, feel free to check my featured posts. See you in the next one.