What is the difference between random.randint and randrange?
The only differences between randrange
and randint
that I know of are that with randrange([start], stop[, step])
you can pass a step
argument and random.randrange(0, 1)
will not consider the last item, while randint(0, 1)
returns a choice inclusive of the last item.
So, I don't understand why randrange(0, 1)
doesn't return 0
or 1
. Why would I use randrange(0, 2)
instead of a randrange(0, 1)
which does?
Solution 1:
The docs on randrange
say:
random.randrange([start], stop[, step])
Return a randomly selected element from
range(start, stop, step)
. This is equivalent tochoice(range(start, stop, step))
, but doesn’t actually build a range object.
And range(start, stop)
returns [start, start+step, ..., stop-1]
, not [start, start+step, ..., stop]
. As for why... zero-based counting rules and range(n)
should return n
elements, I suppose. Most useful for getting a random index, I suppose.
While randint
is documented as:
random.randint(a, b)
Return a random integer N such that
a <= N <= b
. Alias forrandrange(a, b+1)
So randint
is for when you have the maximum and minimum value for the random number you want.
Solution 2:
https://github.com/python/cpython/blob/.../Lib/random.py#L218
def randint(self, a, b):
"""Return random integer in range [a, b], including both end points.
"""
return self.randrange(a, b+1)
Solution 3:
The difference between the two of them is that randint
can only be used when you know both interval limits.
If you only know the first limit of the interval randint
will return an error. In this case you can use randrange
with only one interval and it will work.
Try run the following code for filling the screen with random triangles:
import random
from tkinter import *
tk = Tk()
canvas = Canvas(tk, width=400, height=400)
canvas.pack()
def random_triangle(l1,l2,l3,l4,l5,l6):
x1 = random.randrange(l1)
y1 = random.randrange(l2)
x2 = x1 + random.randrange(l3)
y2 = y1 + random.randrange(l4)
x3 = x2 + random.randrange(l5)
y3 = y2 + random.randrange(l6)
canvas.create_polygon(x1,y1,x2,y2,x3,y3)
for x in range(0, 100):
random_triangle(300,400,200,500,400,100)
Try running again the above code with the randint
function. You will see that you will get an error message.