String to Float Converter

Create a function that attempts to convert a string to a float and returns the float value. Use exception handling to return None if the conversion fails.

Example 1:

Input: "3.14" 
Output: 3.14

Example 2:

Input: "not a number" 
Output: None

Use the built-in float() function to convert the string to a float. Be sure to wrap the operation in a try/except block to handle potential exceptions.

def convert_to_float(value):
    try:
        return float(value)
    except ValueError:
        return None

print(convert_to_float("3.14"))
print(convert_to_float("not a number"))

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!