diff options
author | Raymond Hettinger <rhettinger@users.noreply.github.com> | 2021-12-10 02:24:50 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-12-10 02:24:50 (GMT) |
commit | 3fee7776e6ed8ab023a0220da1daf3160fda868b (patch) | |
tree | 0cbbcea0f930d58f5bf0d659bd187b0390faf61a /Lib/random.py | |
parent | 50669083fe16a42cba90b5dd8c1a017751f69fd8 (diff) | |
download | cpython-3fee7776e6ed8ab023a0220da1daf3160fda868b.zip cpython-3fee7776e6ed8ab023a0220da1daf3160fda868b.tar.gz cpython-3fee7776e6ed8ab023a0220da1daf3160fda868b.tar.bz2 |
Move error test to the function that needs it. Improve error message. (GH-30008)
Diffstat (limited to 'Lib/random.py')
-rw-r--r-- | Lib/random.py | 11 |
1 files changed, 4 insertions, 7 deletions
diff --git a/Lib/random.py b/Lib/random.py index 92a71e1..e8bc941 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -233,10 +233,8 @@ class Random(_random.Random): break def _randbelow_with_getrandbits(self, n): - "Return a random int in the range [0,n). Returns 0 if n==0." + "Return a random int in the range [0,n). Defined for n > 0." - if not n: - return 0 getrandbits = self.getrandbits k = n.bit_length() # don't use (n-1) here because n can be 1 r = getrandbits(k) # 0 <= r < 2**k @@ -245,7 +243,7 @@ class Random(_random.Random): return r def _randbelow_without_getrandbits(self, n, maxsize=1<<BPF): - """Return a random int in the range [0,n). Returns 0 if n==0. + """Return a random int in the range [0,n). Defined for n > 0. The implementation does not use getrandbits, but only random. """ @@ -256,8 +254,6 @@ class Random(_random.Random): "enough bits to choose from a population range this large.\n" "To remove the range limitation, add a getrandbits() method.") return _floor(random() * n) - if n == 0: - return 0 rem = maxsize % n limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0 r = random() @@ -338,7 +334,8 @@ class Random(_random.Random): def choice(self, seq): """Choose a random element from a non-empty sequence.""" - # raises IndexError if seq is empty + if not seq: + raise IndexError('Cannot choose from an empty sequence') return seq[self._randbelow(len(seq))] def shuffle(self, x): |