Python Code To Generate Random Number

Problem Statement

Random number is a series of numbers with unpredictable sequence. Following code will generate random numbers in Python.


  1. Import “random” library which will be used to generate random numbers.
  2. Create a function that will take input number of random numbers to be generated.
  3. In the function, use a for loop to run as many times as the number of random numbers to be genarted.
  4. In for loop return random numbers.

How Does Python Random Generator Work?

The given code above will print “x” random values of numbers between “a” and “b”. In the for loop, range(x) is the number will be the number of random numbers that you’ll have want.

If you want 20 values, use range(20). Use range(5) if you only want 5 values returned, etc. Then the code will automatically select a random integer between “a” and “b” for you.

NOTE:   “a” and “b” should be positive values(including 0) only.

Python Program/Code To Generate Random Numbers

import random # import statement
def random_num(no,a,b):    # function definition
l=[]                       # create an empty list
for x in range(no):        # for loop until number of random numbers to be generated
    l.append(random.randint(a,b)) # append random numbers to the list
return l                   # return the list



  • 97
  • 75
  • 47
  • 88
  • 24
  • 58
  • 13
  • 50
  • 73
  • 58

Leave a Reply