python

How to generate a random number in Python

In this tutorial, we are going to see how to generate a random number in Python. Using ‘random’ module, we can generate pseudo-random numbers. The function random() generates a random number between zero and one [0, 0.1..1]. The numbers generated with this module are not really random but they are random enough for most purposes.

See the code snippet below to see how it works to generate a number between 1 and 100.
 

 

How to generate a random number in Python
import random
for n in range(10):
  print(random.randint(1,101))

Output:

78
92
51
86
70
70
72
74
43
90

The above code will display 10 random values between 1 and 100. The second line, for n in range(10) determines the number of values to display (when you use range(n), the value of n is the number of values you want to display. If you want 20 values, use range(20). Use range(5) if you want only 5 values, etc.). Then the third line: print random.randint(1,101) will automatically select a random integer between 1 and 100 for you.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *