-1

I took this line from online to make a random 4 digit number

number = str(random.randint(0,9999))

but sometimes it give me random 3 digit number why?

Is their a better way to make a random multiple digit number in python

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • Did you read the [docs](https://docs.python.org/3/library/random.html#random.randint) of `randint`? It says: *Return a random integer N such that `a <= N <= b`. Alias for `randrange(a, b+1)`.* So in your code `0` is also an option. It is not 4 digits. Try `randint(1000,9999)` – Tomerikoo Jan 20 '21 at 07:47
  • You should read the base knowledge about random.randint(a, b) - Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1). Detail here: https://docs.python.org/3/library/random.html#random.randint – Vu Phan Jan 20 '21 at 07:49
  • @Tomerikoo It's arguable that most of the answers in the question for which this is marked a duplicate of could be superseded by using `random.choices()`. – mhawke Jan 20 '21 at 08:08
  • @mhawke and? I don't see your point. This is still an obvious duplicate. If you have another solution not existing there, feel free to post it there – Tomerikoo Jan 20 '21 at 08:34
  • @Tomerikoo: fair enough. – mhawke Jan 20 '21 at 10:09

2 Answers2

0

Because you've asked for a number between 0 and 9999 inclusive. That includes single, double and triple digit numbers as well.

If you want only 4 digit numbers start at 1000:

number = str(random.randint(1000, 9999))

See the randint() documentation.

If you want 4 digits that could include leading zeroes then you use random.choices():

from string import digits

number = ''.join(random.choices(digits, k=4))

which picks 4 digits with replacement and joins them into a string.

mhawke
  • 84,695
  • 9
  • 117
  • 138
0
number = str(random.randint(1000,9999))
Harney
  • 352
  • 1
  • 4