Keep Asking Until Valid

Medium ⏱ 12 min 48% acceptance ★★★★★ 4.9
Write ask_int(prompts) simulating a retry prompt: prompts is a list of pre-recorded user inputs. Return the first one that parses as an int; if none do, return None. This mirrors the classic while True: try: ... except: continue input loop, but testable without real input().

Examples

Example 1
Input
ask_int(['abc', ' 7 ', '9'])
Output
7
Explanation

The second entry is the first valid integer.

Constraints

  • Process prompts in order.
  • Whitespace-padded numbers are valid.

Topics

Exception Handlinginput loop

Companies

TCSInfosysCapgemini

Hints

Hint 1

Loop and attempt int() on each.

Hint 2

Return inside the try on success.

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