Last active
October 11, 2017 02:33
-
-
Save snowman2/60b69609905e705b5bcb379addd1b20d to your computer and use it in GitHub Desktop.
the difference between random and randrange
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# import what you need | |
>>> from random import random, randrange | |
# https://docs.python.org/3/library/random.html#random.random | |
# Return the next random floating point number in the range [0.0, 1.0). | |
>>> random() | |
0.04458157505033977 | |
>>> random() | |
0.11730160701010572 | |
# range gives you a list/iterable depending in the Python version and is often used for iterations | |
# http://pythoncentral.io/pythons-range-function-explained | |
# if you just give it a number it starts at 0 and ends at the number-1 | |
>>> list(range(10)) | |
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | |
>>> list(range(2)) | |
[0, 1] | |
# https://docs.python.org/3/library/random.html#random.randrange | |
# Return a randomly selected element from range(start, stop, step). | |
>>> randrange(10) | |
0 | |
>>> randrange(10) | |
2 | |
>>> randrange(10) | |
7 | |
# you can accomplish the same thing with range, however it does not include steps | |
>>> int(random()*10) | |
0 | |
>>> int(random()*10) | |
8 | |
>>> int(random()*10) | |
4 | |
# a if you specify a start and stop, it will limit it to a number | |
# that would have been in the equivalent range call | |
>>> list(range(5, 10)) | |
[5, 6, 7, 8, 9] | |
>>> randrange(5, 10) | |
6 | |
>>> randrange(5, 10) | |
8 | |
>>> randrange(5, 10) | |
9 | |
# you can further limit your selection with steps | |
# in this case, it has an interval of 10 | |
>>> list(range(5, 100, 10)) | |
[5, 15, 25, 35, 45, 55, 65, 75, 85, 95] | |
>>> randrange(5, 100, 10) | |
65 | |
>>> randrange(5, 100, 10) | |
95 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment