The Forgotten else of try

Medium ⏱ 12 min 50% acceptance ★★★★☆ 4.3
Write read_number_line(path) that opens a file, parses its first line as a float and returns ('ok', value) — but returns ('missing', None) if the file doesn't exist and ('invalid', None) if parsing fails. Use try's <code>else</code> clause so the parse only counts as "ok" when no exception occurred in the open/read step being guarded.

Examples

Example 1
Input
read_number_line('temp.txt')  # first line '36.6'
Output
('ok', 36.6)
Explanation

File present and parseable.

Constraints

  • Use an else clause on a try block.
  • Distinguish the two failure modes.

Topics

Exception Handlingtry/else

Companies

GoogleAtlassian

Hints

Hint 1

try/except FileNotFoundError, except ValueError, else: return ok.

Hint 2

The else branch runs only when nothing raised.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.