Python Program to Generate Random Numbers from 1 to 20 and Append Them to the List


When it is required to generate random numbers within a given range and append them to a list, a method is defined, that generates random numbers and ‘append’s them to an empty list.

Below is the demonstration of the same −

Example

 Live Demo

import random
def random_gen(beg, end, my_num):
   my_result = []
   for j in range(my_num):
      my_result.append(random.randint(beg, end))
   return my_result
my_num = 19
beg = 1
end = 20
print("The number is :")
print(my_num)
print("The start and end values are :")
print(beg, end)
print("The elements are : ")
print(random_gen(beg, end, my_num))

Output

The number is :
19
The start and end values are :
1 20
The elements are :
[12, 12, 5, 12, 11, 1, 5, 12, 19, 19, 7, 15, 18, 18, 10, 14, 3, 2, 11]

Explanation

  • A method named ‘random_gen’ is defined, that takes three parameters- the beginning, end and a number.

  • The method generates random numbers with the range of ‘beginning’ and ‘end’.

  • It appends it to a list.

  • Outside the method, three values are defined.

  • They are displayed on the console.

  • The method is called by passing this values as parameters.

  • The output is displayed on the console.

Updated on: 19-Apr-2021

383 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements