How to Generate a Random Number in Python

Published by

Posted on December 16, 2017

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

import random
for x in range(10):
  print random.randint(1,101)

The code above will print 10 random values of numbers between 1 and 100. The second line, for x in range(10), determines how many values will be printed (when you use range(x), the number that you use in place of x will be the amount of values that you’ll have printed. if you want 20 values, use range(20). use range(5) if you only want 5 values returned, etc.). Then the third line: print random.randint(1,101) will automatically select a random integer between 1 and 100 for you. The process is fairly simple.



About the Author