A summary of the basic functions of the random module.
Specify smaller in the range specification.
random.randrange (initial value, end value, step)
** ▼ Specify only the end value ** For one argument, specify the ending value (less than).
print(random.randrange(1))
print(random.randrange(10))
print(random.randrange(10000))
#output
0
4
5310
-If the argument is 1, the corresponding integer is only 0. ・ In the case of 10, 0 to 9 ・ Minus cannot be specified
If negative, error
print(random.randrange(-10))
#output
# ValueError: empty range for randrange()
print(random.randrange(5,10))
print(random.randrange(-5,10))
print(random.randrange(-5,-1))
#output
5
3
-5
print(random.randrange(6,10,2))
print(random.randrange(-6,10,2))
print(random.randrange(-6,-10,-2))
#output
8
0
-6
** Error if step is out of range **
Steps out of range are in error
print(random.randrange(-6,-10,2))
print(random.randrange(6,10,-2))
#output
# ValueError: empty range for randrange()
print(random.randint(6,10))
print(random.randint(-6,10))
#output
7
-5
** ▼ Step cannot be specified **
Specifying a step is an error
print(random.randint(6,10,2))
#output
TypeError: randint() takes 3 positional arguments but 4 were given
python
print(random.random())
#output
0.006672554597154434
** ▼ Error when passing arguments **
Error when passing arguments
print(random.random(3))
#output
TypeError: random() takes no arguments (1 given)
random.uniform (initial value, end value)
└ Above and below (including)
└ Minus is OK
└ Initial value and end value can be exchanged (automatic judgment)
python
print(random.uniform(1,3))
print(random.uniform(3,1))
print(random.uniform(-3,-1))
print(random.uniform(-1,-3))
#output
2.5435117820109165
1.0971805105781995
-1.8504872730735842
-2.7854383306809494
x = range(10)
y = [1, 6]
z = [1.1, 6.7]
w = range(-20, -4)
v = [-2, -7]
print(random.choice([3,5,6,8]))
print(random.choice(x))
print(random.choice(y))
print(random.choice(z))
print(random.choice(w))
print(random.choice(v))
#output
8
5
1
6.7
-10
-7
Recommended Posts