In Python, just like in almost any other OOP language, chances are that you'll find yourself needing to generate a random number at some point. Whether you're just completing an exercise in algorithms to better familiarize yourself with the language, or if you're trying to write more complex code, you can't call yourself a Python coder without knowing how to generate random numbers.

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.

What if, however, you wanted to select a random integer that was between 1 and 100 but also a multiple of five? This is a little more complicated. The process is the same, but you'll need to use a little more arithmetic to make sure that the random integer is in fact a multiple of five. Check out the code below:

import random
for x in range(10):
  print random.randint(1,21)*5,
print

Basically this code will generate a random number between 1 and 20, and then multiply that number by 5. So not only will every number printed be a multiple of 5, but the highest number that can be printed is 100 (20*5=100). Play around with the code yourself and see if you can generate a random number between 1-100 where every number generated is a multiple of ten!

To Practice: Try this interactive course on the basics of Lists, Functions, Packages and NumPy in Python.

  • Jatin Verma

    random.randint(1,101) can output 101 in my version of python!?