diff --git a/Lib/random.py b/Lib/random.py index 7db761034509d37..7cf18ceee5482d4 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -1067,15 +1067,17 @@ def main(arg_list: list[str] | None = None) -> int | str: try: # Is it an integer? val = int(val) - return randint(1, val) except ValueError: try: # Is it a float? val = float(val) - return uniform(0, val) except ValueError: # Split in case of space-separated string: "a b c" return choice(val.split()) + else: + return uniform(0, val) + else: + return randint(1, val) if len(args.input) >= 2: return choice(args.input) @@ -1084,4 +1086,8 @@ def main(arg_list: list[str] | None = None) -> int | str: if __name__ == '__main__': - print(main()) + import sys + try: + print(main()) + except ValueError as exc: + sys.exit(f"error: {exc}") diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py index 8d093ab1b7014a4..5fb24b380df7514 100644 --- a/Lib/test/test_random.py +++ b/Lib/test/test_random.py @@ -15,6 +15,7 @@ from collections import abc, Counter from test.support import warnings_helper +from test.support.script_helper import assert_python_failure class MyIndex: @@ -1482,6 +1483,18 @@ def test_main(self): random.seed(0) self.assertEqual(random.main(shlex.split(command)), expected) + def test_empty_integer_range_error(self): + # An integer input is the same as --integer, even when it is + # not positive. + for value in ["0", "-5"]: + for args in [(value,), ("--integer", value)]: + with self.subTest(args=args): + rc, out, err = assert_python_failure("-m", "random", *args) + self.assertEqual(rc, 1) + self.assertEqual(out, b"") + expected = f"error: empty range in randint(1, {value})" + self.assertEqual(err.decode().rstrip(), expected) + if __name__ == "__main__": unittest.main() diff --git a/Misc/NEWS.d/next/Library/2026-11-05-22-26-44.gh-issue-161452.YfFfjq.rst b/Misc/NEWS.d/next/Library/2026-11-05-22-26-44.gh-issue-161452.YfFfjq.rst new file mode 100644 index 000000000000000..f8b9e245e6f4413 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-05-22-26-44.gh-issue-161452.YfFfjq.rst @@ -0,0 +1,4 @@ +Fix the :mod:`random` :ref:`command-line interface ` +printing a random float for a zero or negative integer input instead of +failing like ``--integer`` does. Both now report a short error message +instead of a traceback.