Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Validate integer inputE02. Safe divide with a default valueE03. Parse a float or return NoneE

Problem No 3

Parse a float or return None

Easy

10 minute session

Summary

Convert strings to floats robustly and reject non-finite results.

Problem statement

Floating-point parsing using float(s) can produce special values like NaN or infinity. Implement parse_float(s) that attempts to convert s to a Python float. If conversion fails or the result is not a finite number (NaN or infinite), return None. The function should tolerate leading/trailing whitespace. It should not accept empty strings or None.

Task

Implement a parser that returns a float for valid numeric strings, otherwise returns None (including for NaN and infinities).

Examples

simple decimal

Input

parse_float('3.14')

Output

3.14

Explanation

Converts the string to the float 3.14.

scientific notation

Input

parse_float(' -2e2 ')

Output

-200.0

Explanation

Scientific notation with whitespace is parsed and returned as a finite float.

Input format

Call parse_float(s) where s is typically a string representing a number.

Output format

Return a float for valid finite numbers, otherwise return None.

Constraints

Reject NaN and infinities by returning None. Use math.isfinite to check finiteness. Do not accept non-string, non-numeric inputs silently; attempt to cast via float() and handle exceptions.

Samples

Sample input 0

parse_float('')

Sample output 0

Explanation 0

Empty string is invalid and returns None.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

03:43 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.