How to write a function that takes a number n
and return a randomly generated number having exactly n
digits (except starting with 0). e.g. if n
is 2 then function can randomly return a number in range 10-99 but 07,02 etc. are not valid two digit number.
Asked
Active
Viewed 1,161 times
-1

Cody Gray - on strike
- 239,200
- 50
- 490
- 574

JAGRITI VASHISHT
- 7
- 2
-
2_How to avoid using 0 as first digit?.._ Seems you already have implemented the rest of the requirement - Where is that code? – B001ᛦ Jun 26 '19 at 10:33
-
You basically answered your own question: *"if n is 2 then function can randomly return a number __in range 10-99__"* - [`random.randint(10, 99)`](https://docs.python.org/3/library/random.html#random.randint)... – Tomerikoo Jul 04 '21 at 14:25
1 Answers
2
Here is a function that gets as input the number of digits ndigits
, and returns a random number with ndigits
digits. I use powers of 10 to get the range of numbers with ndigits
digits.
import random
...
def random_ndigits(ndigits):
min_num = 10 ** (ndigits - 1)
max_num = (10 ** ndigits) - 1
if ndigits == 1:
min_num = 0
return random.randint(min_num, max_num)

Eliahu Aaron
- 4,103
- 5
- 27
- 37