Generating Random Numbers in Python is very easy. If you have basic understanding of python programming you can write this program in very less time. You can use any Python IDE such as IDLE or Pycharm or you can use Google Collab to write Program.
In Python Random number can be generated by importing random module.
Generating a Random Number
Step 1 : import random module
import random
Step 2: Use random() method.
import random
num = random.random()
print(“The Random number generated is: “, num)
The output of above program is :
The Random number generated is: 0.4280222232647157
In every run you will get different random number. Also you can generate random number with in a given range.
Generate Random Number in a Range
To generate a random number with in a given range you can use randint(range_from,range_to) method. Here first parameter in the method will be the starting range and second parameter will be the Ending range.
import random
num = random.randint(0,30)
print(“The random number is : “, num)
It will generate random number between 0 to 30. The output of above code is:
The Random number generated is : 5
You can generate a list of random numbers . Let’s see how to generate sequence of random numbers using for loop.
Generating A List Of Random Numbers Using For Loop
import random
randomlistofnumbers = []
for i in range(0,5):
num = random.randint(1,30)
randomlistofnumbers .append(num)
print(“List of Random Numbers : “, randomlistofnumbers )
Here you will be able to see list of random numbers generated. The output of above for loop is:
List of Random Numbers : [26, 29, 2, 17, 20]
I hope this post will be helpful to you. Happy Coding!