How to Validate CLI Integer Option Within a Range in Python

Use argparse with integer type and bounds checking to validate a command-line option falls within a specified min-max range.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 14 views 0 copies

Python code

17 lines
Python 3.9+
import argparse

def main():
    parser = argparse.ArgumentParser(description="Validate an integer within a range.")
    parser.add_argument("--value", type=int, required=True, help="Integer to validate")
    parser.add_argument("--min", type=int, default=0, help="Minimum allowed value")
    parser.add_argument("--max", type=int, default=100, help="Maximum allowed value")
    args = parser.parse_args()

    if not (args.min <= args.value <= args.max):
        raise SystemExit(
            f"Error: value {args.value} out of range [{args.min}, {args.max}]"
        )
    print(f"Valid: {args.value} is within [{args.min}, {args.max}]")

if __name__ == "__main__":
    main()

Output

stdout
$ python app.py --value 50
Valid: 50 is within [0, 100]

$ python app.py --value 150
Error: value 150 out of range [0, 100]

How it works

The type=int parameter in add_argument converts the CLI string to an integer immediately. The script then compares the parsed value against the min and max defaults using Python's chained comparison operator. If the value falls outside the range, SystemExit terminates the program with a clear error message. The required=True flag ensures the user supplies a --value argument, preventing a missing-argument crash.

Common mistakes

  • Calling `parser.parse_args()` inside `main()` but referencing `args` before the parser is fully defined.
  • Forgetting to set `required=True` on the value argument, allowing a missing value to slip through.
  • Using separate `if` statements instead of the chained comparison, making the logic harder to read.

Variations

  1. Use `type=lambda x: int(x)` to add custom validation logic before the range check.
  2. Implement range validation directly inside a custom `argparse.Action` class for reuse.

Real-world use cases

  • Enforcing page-size limits on a paginated API client CLI tool.
  • Validating port numbers in a network diagnostic script before opening a socket.
  • Checking that an age or expiry period in a batch processing job stays within business rules.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.