What is the difference between random randint and randrange?

前端 未结 5 1922
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-07 16:25

The only difference that I know between randrange and randint is that randrange([start], stop[, step]) you can use the step and

5条回答
  •  清歌不尽
    2020-12-07 17:05

    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.

提交回复
热议问题