Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Convert text to int with a range check

Safely parse a string to an integer and ensure it lies within a specified inclusive range.

Python practice15 minError Handling & Edge CasesIntermediateLast updated March 20, 2026

Problem statement

Implement parse_int_in_range(text, min_val, max_val) that: - Accepts text (possibly with surrounding whitespace), min_val, and max_val (integers). - Returns the integer value if text represents an integer in base 10 and min_val <= value <= max_val. - Returns None for invalid conversions (non-integer text like '3.0', 'abc', empty string), or when the parsed integer is outside the inclusive range. - Leading zeros and an optional leading '+' or '-' are allowed (e.g., '+0012' -> 12). Be defensive: avoid raising exceptions for malformed input and ensure whole-string integer semantics (no partial parsing).

Task

Implement a conversion function that returns an integer when the text is a valid integer inside the given bounds, otherwise return None.

Examples

Basic valid integer

Input

parse_int_in_range(' 42 ', 0, 100)

Output

42

Whitespace is trimmed; 42 is within [0, 100].

Input format

Three arguments: text (string), min_val (int), max_val (int).

Output format

Return parsed integer if valid and in range, otherwise return None.

Constraints

Do not use float conversions to detect integers. Ensure entire string (after strip) is an integer literal.

Samples

Sample 1

Input

parse_int_in_range('-5', -10, 0)

Output

-5

Negative values are supported and must be within the provided bounds.