Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The docs on randrange say:

random.randrange([start], stop[, step])

Return a randomly selected element from range(start, stop, step). This is equivalent to choice(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 for randrange(a, b+1)

So randint is for when you have the maximum and minimum value for the random number you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...