Let’s say I need a 3-digit number, so it would be something like:
JavaScript
x
10
10
1
>>> random(3)
2
563
3
4
or
5
6
>>> random(5)
7
26748
8
>> random(2)
9
56
10
Advertisement
Answer
You can use either of random.randint
or random.randrange
. So to get a random 3-digit number:
JavaScript
1
5
1
from random import randint, randrange
2
3
randint(100, 999) # randint is inclusive at both ends
4
randrange(100, 1000) # randrange is exclusive at the stop
5
* Assuming you really meant three digits, rather than “up to three digits”.
To use an arbitrary number of digits:
JavaScript
1
11
11
1
from random import randint
2
3
def random_with_N_digits(n):
4
range_start = 10**(n-1)
5
range_end = (10**n)-1
6
return randint(range_start, range_end)
7
8
print random_with_N_digits(2)
9
print random_with_N_digits(3)
10
print random_with_N_digits(4)
11
Output:
JavaScript
1
4
1
33
2
124
3
5127
4