summaryrefslogtreecommitdiffstats
path: root/Lib/random.py
diff options
context:
space:
mode:
authorAntoine Pitrou <antoine@python.org>2020-04-17 17:32:14 (GMT)
committerGitHub <noreply@github.com>2020-04-17 17:32:14 (GMT)
commit75a3378810bab03949ad9f653f78d933bdf3879c (patch)
tree96ec61f0d287ca5632da7ee091079817d4197733 /Lib/random.py
parentd7c657d4b121164caa439253da5266b2e29a1bed (diff)
downloadcpython-75a3378810bab03949ad9f653f78d933bdf3879c.zip
cpython-75a3378810bab03949ad9f653f78d933bdf3879c.tar.gz
cpython-75a3378810bab03949ad9f653f78d933bdf3879c.tar.bz2
bpo-40282: Allow random.getrandbits(0) (GH-19539)
Diffstat (limited to 'Lib/random.py')
-rw-r--r--Lib/random.py6
1 files changed, 4 insertions, 2 deletions
diff --git a/Lib/random.py b/Lib/random.py
index 82345fa..3243938 100644
--- a/Lib/random.py
+++ b/Lib/random.py
@@ -261,6 +261,8 @@ class Random(_random.Random):
def _randbelow_with_getrandbits(self, n):
"Return a random int in the range [0,n). Raises ValueError if n==0."
+ if not n:
+ raise ValueError("Boundary cannot be zero")
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
@@ -733,8 +735,8 @@ class SystemRandom(Random):
def getrandbits(self, k):
"""getrandbits(k) -> x. Generates an int with k random bits."""
- if k <= 0:
- raise ValueError('number of bits must be greater than zero')
+ if k < 0:
+ raise ValueError('number of bits must be non-negative')
numbytes = (k + 7) // 8 # bits / 8 and rounded up
x = int.from_bytes(_urandom(numbytes), 'big')
return x >> (numbytes * 8 - k) # trim excess bits