F
F
fantom_ask2020-08-12 14:32:03
Python
fantom_ask, 2020-08-12 14:32:03

How to get four random numbers in a row?

I'm new to python so I don't know if my version is better

import random
random_number = ''
for x in range(4):
  random_number = random_number + str(random.randint(0, 9))

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
aRegius, 2020-08-12
@fantom_ask

random.choices(range(10), k=4)

S
ScriptKiddo, 2020-08-12
@ScriptKiddo

Quite. Shorter, but less readable, can be written like this:

import random
random_digits = 3
print(''. join([str(random.randint(0, 9)) for _ in range(random_digits)]))

A
Andrey, 2020-08-12
@anerev

If you don't need repeats

from random import randint
random_number = ""

while len(random_number) < 4:
    a = str(randint(0, 9))
    if a not in random_number:
        random_number += a

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question