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/exceptblock. - If the
tryblock run successfully, it indicates that the value is convertible to float. - If the
exceptblock is executed, it indicates that the value cannot be converted to float.
value = '3.14'
try:
result = float(value)
print("Value is convertible to float")
except ValueError:
print('Value is not convertible 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:
def convertable_to_float(string):
try:
result = float(string)
return True
except ValueError:
return False
print(convertable_to_float('3.14'))
print(convertable_to_float('1000'))
print(convertable_to_float('sharooq.com'))
print(convertable_to_float('0.8'))
if convertable_to_float('1111'):
print("Value is convertible to float")
else:
print('Value is not convertible to float')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.
