How to random number generator 1-100 in Python?

Dung Do Tien Jul 31 2021 65

I have created a small project with Python, I want to get 5 random numbers from 0 to 100. For example:

0,34,23,89,76

And they can not duplicate. I try as below:

 import numpy as np   
number = np.random.randint(100)
print(number)

But it only return one number and I try with loop but they was duplicated. 

So how can I get 5 random numbers from 1 to 100 in Python?

Thanks for any suggesstions.

Have 3 answer(s) found.
  • Đ

    Đặng Thanh Tuấn Jul 31 2021

    See an example as below:

     import numpy as np
    totalReturnNumbers = 5 # If you only get one number, change value to 1
    ramdomFrom = 0
    ramdomTo = 100
    numbers = [np.random.randint(ramdomFrom, ramdomTo) for x in range(totalReturnNumbers)]
    print(numbers)

    1st > [67, 61, 97, 67, 97]

    2nd> [88, 2, 23, 88, 61]

    3rd> [53, 59, 90, 81, 69]

    I hope it resolve for you.

  • G

    Giang Nguyen Jul 31 2021

    You can use numpy package to help get array random numbers. See simple code below:

     import numpy as np   
    numbers = np.random.randint(100, size=(1, 5))
    print(numbers) # return > [[19 24 71 89 44]]

    And it works for me.

  • P

    Peter Melling Jul 31 2021

    You can use uniform() method of numpy package to help get a list of random numbers.

     import numpy as np
    numbers = np.random.uniform(low=0, high=100, size=(5,)).astype(int)
    print (numbers) # return random > [37 16  5 67 82]

    It seems very easy!!

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close