Login
📚 Python for Introductory Statistics
Chapters ▾

Appendix 2: Random Integer Generator

Watch demo video

"A random number generator, generates a sequence of numbers or symbols that cannot be reasonably predicted better than by a random chance." Wikipedia

To randomly generate n integers between a and b, inclusive, use the following function from the numpy library. Here n,a and b are integers.

import numpy as np  
np.random.randint(a, b+1, size=n)

The above code returns an array of n random integers from a to b+1, inclusive. Notice that every time you run the program, it will generate different sets of numbers. To create the same set of random numbers you can add the line np.random.seed(123).

Example: Write a program to randomly select one integer between 1 and 10.

  1. Click + Code
  2. Type import numpy as np
  3. Type np.random.randint(1,10+1,size=1)
  4. Click play button
import numpy as np
np.random.randint(1,10+1,size=1) 
Show expected output
array([5])

Interpretation: The number 5 is randomly selected from all integers between 1 and 10. If you run this program again, it will, most likely, generate a different result.

Adapted from Python for Introductory Statistics, by Simon Aman (Truman College, City Colleges of Chicago), licensed under CC BY 4.0. Changes were made: reformatted as an accessible XYZ web edition with live in-browser code cells. License: CC-BY-4.0.