Let say I need a 3 digit number, so it would be something like:
>>> random(3)
563
or
>>> random(5)
26748
>> random(2)
56
Let say I need a 3 digit number, so it would be something like:
>>> random(3)
563
or
>>> random(5)
26748
>> random(2)
56
To get a random 3-digit number:
from random import randint
randint(100, 999) # randint is inclusive at both ends
(assuming you really meant three digits, rather than "up to three digits".)
To use an arbitrary number of digits:
from random import randint
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
print random_with_N_digits(2)
print random_with_N_digits(3)
print random_with_N_digits(4)
Output:
33
124
5127
Does 0 count as a possible first digit? If so, then you need random.randint(0,10**n-1)
. If not, random.randint(10**(n-1),10**n-1)
. And if zero is never allowed, then you'll have to explicitly reject numbers with a zero in them, or draw n
random.randint(1,9)
numbers.
Aside: it is interesting that randint(a,b)
uses somewhat non-pythonic "indexing" to get a random number a <= n <= b
. One might have expected it to work like range
, and produce a random number a <= n < b
. (Note the closed upper interval.)
Given the responses in the comments about randrange
, note that these can be replaced with the cleaner random.randrange(0,10**n)
, random.randrange(10**(n-1),10**n)
and random.randrange(1,10)
.
You could write yourself a little function to do what you want:
import random
def randomDigits(digits):
lower = 10**(digits-1)
upper = 10**digits - 1
return random.randint(lower, upper)
Basically, 10**(digits-1)
gives you the smallest {digit}-digit number, and 10**digits - 1
gives you the largest {digit}-digit number (which happens to be the smallest {digit+1}-digit number minus 1!). Then we just take a random integer from that range.