Random Numbers with the Python Standard Library
The Python standard library provides a module called random that offers a suite of functions for generating random numbers.
Python uses a popular and robust pseudorandom number generator called the Mersenne Twister.
In this section, we will look at a number of use cases for generating and using random numbers and randomness with the standard Python API.
Need help with Statistics for Machine Learning?
Take my free 7day email crash course now (with sample code).
Click to signup and also get a free PDF Ebook version of the course.
Seed The Random Number Generator
The pseudorandom number generator is a mathematical function that generates a sequence of nearly random numbers.
It takes a parameter to start off the sequence, called the seed. The function is deterministic, meaning given the same seed, it will produce the same sequence of numbers every time. The choice of seed does not matter.
The seed() function will seed the pseudorandom number generator, taking an integer value as an argument, such as 1 or 7. If the seed() function is not called prior to using randomness, the default is to use the current system time in milliseconds from epoch (1970).
The example below demonstrates seeding the pseudorandom number generator, generates some random numbers, and shows that reseeding the generator will result in the same sequence of numbers being generated.
10 11 
# seed the pseudorandom number generator from random import seed from random import random # seed random number generator seed(1) # generate some random numbers print(random(), random(), random()) # reset the seed seed(1) # generate some random numbers print(random(), random(), random()) 
Running the example seeds the pseudorandom number generator with the value 1, generates 3 random numbers, reseeds the generator, and shows that the same three random numbers are generated.
0.13436424411240122 0.8474337369372327 0.763774618976614 0.13436424411240122 0.8474337369372327 0.763774618976614 
It can be useful to control the randomness by setting the seed to ensure that your code produces the same result each time, such as in a production model.
For running experiments where randomization is used to control for confounding variables, a different seed may be used for each experimental run.
Random Floating Point Values
Random floating point values can be generated using the random() function. Values will be generated in the range between 0 and 1, specifically in the interval [0,1).
Values are drawn from a uniform distribution, meaning each value has an equal chance of being drawn.
The example below generates 10 random floating point values.
# generate random floating point values from random import seed from random import random # seed random number generator seed(1) # generate random numbers between 01 for _ in range(10): value = random() print(value) 
Running the example generates and prints each random floating point value.
10 
0.13436424411240122 0.8474337369372327 0.763774618976614 0.2550690257394217 0.49543508709194095 0.4494910647887381 0.651592972722763 0.7887233511355132 0.0938595867742349 0.02834747652200631 
The floating point values could be rescaled to a desired range by multiplying them by the size of the new range and adding the min value, as follows:
scaled value = min + (value * (max – min)) 
Where min and max are the minimum and maximum values of the desired range respectively, and value is the randomly generated floating point value in the range between 0 and 1.
Random Integer Values
Random integer values can be generated with the randint() function.
This function takes two arguments: the start and the end of the range for the generated integer values. Random integers are generated within and including the start and end of range values, specifically in the interval [start, end]. Random values are drawn from a uniform distribution.
The example below generates 10 random integer values between 0 and 10.
# generate random integer values from random import seed from random import randint # seed random number generator seed(1) # generate some integers for _ in range(10): value = randint(0, 10) print(value) 
Running the example generates and prints 10 random integer values.
10 
10 
Random Gaussian Values
Random floating point values can be drawn from a Gaussian distribution using the gauss() function.
This function takes two arguments that correspond to the parameters that control the size of the distribution, specifically the mean and the standard deviation.
The example below generates 10 random values drawn from a Gaussian distribution with a mean of 0.0 and a standard deviation of 1.0.
Note that these parameters are not the bounds on the values and that the spread of the values will be controlled by the bell shape of the distribution, in this case proportionately likely above and below 0.0.
# generate random Gaussian values from random import seed from random import gauss # seed random number generator seed(1) # generate some Gaussian values for _ in range(10): value = gauss(0, 1) print(value) 
Running the example generates and prints 10 Gaussian random values.
10 
1.2881847531554629 1.449445608699771 0.06633580893826191 0.7645436509716318 1.0921732151041414 0.03133451683171687 1.022103170010873 1.4368294451025299 0.19931197648375384 0.13337460465860485 
Note: In the random module, there is a function
normalvariate()
that functions the same as
gauss()
. The former is threadsafe while
gauss()
is not. However, you rarely run Python in multithread and
gauss()
is faster.
Randomly Choosing From a List
Random numbers can be used to randomly choose an item from a list.
For example, if a list had 10 items with indexes between 0 and 9, then you could generate a random integer between 0 and 9 and use it to randomly select an item from the list. The choice() function implements this behavior for you. Selections are made with a uniform likelihood.
The example below generates a list of 20 integers and gives five examples of choosing one random item from the list.
10 11 12 
# choose a random element from a list from random import seed from random import choice # seed random number generator seed(1) # prepare a sequence sequence = [i for i in range(20)] print(sequence) # make choices from the sequence for _ in range(5): selection = choice(sequence) print(selection) 
Running the example first prints the list of integer values, followed by five examples of choosing and printing a random value from the list.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 18 
Random Subsample From a List
We may be interested in repeating the random selection of items from a list to create a randomly chosen subset.
Importantly, once an item is selected from the list and added to the subset, it should not be added again. This is called selection without replacement because once an item from the list is selected for the subset, it is not added back to the original list (i.e. is not made available for reselection).
This behavior is provided in the sample() function that selects a random sample from a list without replacement. The function takes both the list and the size of the subset to select as arguments. Note that items are not actually removed from the original list, only selected into a copy of the list.
The example below demonstrates selecting a subset of five items from a list of 20 integers.
10 11 
# select a random sample without replacement from random import seed from random import sample # seed random number generator seed(1) # prepare a sequence sequence = [i for i in range(20)] print(sequence) # select a subset without replacement subset = sample(sequence, 5) print(subset) 
Running the example first prints the list of integer values, then the random sample is chosen and printed for comparison.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] [4, 18, 2, 8, 3] 
Randomly Shuffle a List
Randomness can be used to shuffle a list of items, like shuffling a deck of cards.
The shuffle() function can be used to shuffle a list. The shuffle is performed in place, meaning that the list provided as an argument to the shuffle() function is shuffled rather than a shuffled copy of the list being made and returned.
The example below demonstrates randomly shuffling a list of integer values.
10 11 
# randomly shuffle a sequence from random import seed from random import shuffle # seed random number generator seed(1) # prepare a sequence sequence = [i for i in range(20)] print(sequence) # randomly shuffle the sequence shuffle(sequence) print(sequence) 
Running the example first prints the list of integers, then the same list after it has been randomly shuffled.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] [11, 5, 17, 19, 9, 0, 16, 1, 15, 6, 10, 13, 14, 12, 7, 3, 8, 2, 18, 4] 
Further Reading: Probability Theory and Statistical Analysis
If you’re interested in the theory behind random number generation, consider studying probability theory. And if you want to apply random number generation in data analysis, look into statistical analysis in Python. Both topics will provide a deeper understanding of the power and potential of Python’s
randint()
function.
Further Resources for Python Modules
For a more profound understanding of Python Modules, we have gathered several insightful resources for you:
 Python Modules Fundamentals Covered – Dive deep into Python’s module caching and reload mechanisms.

Implementing Queues in Python – Dive into various queue types, including FIFO and LIFO, in Python.

Simplifying Random Data Generation in Python – Learn how to add randomness to your Python programs with “random.”

Python’s Random Module – Learn about the random module and generating random numbers with this Programiz guide.

How to Create Random Numbers in Python – A Medium article that delves into generating random numbers in Python.

Python’s Random Tutorial – A tutorial by Real Python covering topics related to generating random numbers in Python.
Explore these resources, and you’ll be taking another stride towards expertise in Python and taking your coding abilities to the next level.
Python3

Output :
Traceback (most recent call last):
File “/home/fb805b21fea0e29c6a65f62b99998953.py”, line 5, in
r2=random.randint(‘a’, ‘z’)
File “/usr/lib/python3.5/random.py”, line 218, in randint
return self.randrange(a, b+1)
TypeError: Can’t convert ‘int’ object to str implicitly
Applications : The randint() function can be used to simulate a lucky draw situation. Let’s say User has participated in a lucky draw competition. The user gets three chances to guess the number between 1 and 10. If guess is correct user wins, else loses the competition.
Random Numbers
To generate random numbers, first import the randint command section from Python’s random code library on the first line of the program.
The randint command stands for random integer. In brackets, state the number range to randomly choose from.
The random value should be saved into a variable.
from random import randint
number = randint(1,100)
print(“A random number between 1 and 100 is” , number)
A random number between 1 and 100 is 39
A random number between 1 and 100 is 73
A random number between 1 and 100 is 4
The randint range does not have to be fixed values and could be replaced by variables.
Below is a program where the user selects the upper and lower values of the range:
from random import randint
lower = int(input(“What is the lowest number? “))
upper = int(input(“What is the highest number? “))
number = randint(lower,upper)
print(“A random number between” , lower , “and” , upper , “is” , number)
What is the lowest number? 1What is the highest number? 50A random number between 1 and 50 is 36
What is the lowest number? 500What is the highest number? 1000A random number between 500 and 1000 is 868
Random Numbers Task 1 (Ice Comet)
A special comet made of ice passes the Earth only once every one hundred years, and it hasn’t been seen yet in the 21st century.
Use the randint command to randomly print a year between the current year and 2099.
Example solutions:
Did you know it won’t be until 2032 that the ice comet will next pass Earth!?
Did you know it won’t be until 2075 that the ice comet will next pass Earth!?
Random Numbers Task 2 (Guess the Number)
Use randint to generate a random number between 1 and 5.
Ask the user to enter a guess for the number with int and input.
Print the random number and use an if statement to check if there is a match, printing an appropriate statement if there is and something different if there is not a match.
Example solutions:
Enter a number between 1 and 5: 4Computer’s number: 5No match this time!
Enter a number between 1 and 5: 3Computer’s number: 3Well guessed! It’s a match!
Further Reading: Probability Theory and Statistical Analysis
If you’re interested in the theory behind random number generation, consider studying probability theory. And if you want to apply random number generation in data analysis, look into statistical analysis in Python. Both topics will provide a deeper understanding of the power and potential of Python’s
randint()
function.
Further Resources for Python Modules
For a more profound understanding of Python Modules, we have gathered several insightful resources for you:
 Python Modules Fundamentals Covered – Dive deep into Python’s module caching and reload mechanisms.

Implementing Queues in Python – Dive into various queue types, including FIFO and LIFO, in Python.

Simplifying Random Data Generation in Python – Learn how to add randomness to your Python programs with “random.”

Python’s Random Module – Learn about the random module and generating random numbers with this Programiz guide.

How to Create Random Numbers in Python – A Medium article that delves into generating random numbers in Python.

Python’s Random Tutorial – A tutorial by Real Python covering topics related to generating random numbers in Python.
Explore these resources, and you’ll be taking another stride towards expertise in Python and taking your coding abilities to the next level.
Expanding the Range of randint
Python’s
randint()
function isn’t limited to small ranges. In fact, you can generate random integers in any range you like. For example, if you’re simulating a lottery draw, you might need to generate numbers between 1 and 1000:
import random lottery_number = random.randint(1, 1000) print(lottery_number) # Output: # (A random number between 1 and 1000)
In this example, we’ve expanded the range of
randint()
to generate a random number between 1 and 1000. This demonstrates the flexibility of the
randint()
function.
Understanding Python’s randint Function
Python’s
randint()
is a function that belongs to the
random
module. It is used to generate a random integer within a defined range. The function takes two parameters: the start and end of the range, inclusive.
Using randint: A Simple Example
Let’s look at a simple code example to understand how
randint()
works:
import random number = random.randint(1, 10) print(number) # Output: # (A random number between 1 and 10)
In this example,
import random
is used to import the random module, which contains the randint function. Next,
random.randint(1, 10)
is used to generate a random integer between 1 and 10, inclusive. The result is then stored in the variable
number
, which is printed out.
Parameters and Return Value
The
randint(a, b)
function takes two parameters:
 : The lower limit of the range (inclusive).
 : The upper limit of the range (inclusive).
The function returns a random integer such that
a <= N <= b
.
Understanding the Output
The output of the
randint()
function is a random integer within the specified range. In our example, the output is a random number between 1 and 10. Each time you run the code, you might get a different number because the selection is random.
By understanding the basics of Python’s
randint()
function, you can start to harness the power of random number generation in your coding projects.
Random Numbers with NumPy
In machine learning, you are likely using libraries such as scikitlearn and Keras.
These libraries make use of NumPy under the covers, a library that makes working with vectors and matrices of numbers very efficient.
NumPy also has its own implementation of a pseudorandom number generator and convenience wrapper functions.
NumPy also implements the Mersenne Twister pseudorandom number generator.
Let’s look at a few examples of generating random numbers and using randomness with NumPy arrays.
Seed The Random Number Generator
The NumPy pseudorandom number generator is different from the Python standard library pseudorandom number generator.
Importantly, seeding the Python pseudorandom number generator does not impact the NumPy pseudorandom number generator. It must be seeded and used separately.
The seed() function can be used to seed the NumPy pseudorandom number generator, taking an integer as the seed value.
The example below demonstrates how to seed the generator and how reseeding the generator will result in the same sequence of random numbers being generated.
10 11 
# seed the pseudorandom number generator from numpy.random import seed from numpy.random import rand # seed random number generator seed(1) # generate some random numbers print(rand(3)) # reset the seed seed(1) # generate some random numbers print(rand(3)) 
Running the example seeds the pseudorandom number generator, prints a sequence of random numbers, then reseeds the generator showing that the exact same sequence of random numbers is generated.
[4.17022005e01 7.20324493e01 1.14374817e04] [4.17022005e01 7.20324493e01 1.14374817e04] 
Array of Random Floating Point Values
An array of random floating point values can be generated with the rand() NumPy function.
If no argument is provided, then a single random value is created, otherwise the size of the array can be specified.
The example below creates an array of 10 random floating point values drawn from a uniform distribution.
# generate random floating point values from numpy.random import seed from numpy.random import rand # seed random number generator seed(1) # generate random numbers between 01 values = rand(10) print(values) 
Running the example generates and prints the NumPy array of random floating point values.
[4.17022005e01 7.20324493e01 1.14374817e04 3.02332573e01 1.46755891e01 9.23385948e02 1.86260211e01 3.45560727e01 3.96767474e01 5.38816734e01] 
Array of Random Integer Values
An array of random integers can be generated using the randint() NumPy function.
This function takes three arguments, the lower end of the range, the upper end of the range, and the number of integer values to generate or the size of the array. Random integers will be drawn from a uniform distribution including the lower value and excluding the upper value, e.g. in the interval [lower, upper).
The example below demonstrates generating an array of random integers.
# generate random integer values from numpy.random import seed from numpy.random import randint # seed random number generator seed(1) # generate some integers values = randint(0, 10, 20) print(values) 
Running the example generates and prints an array of 20 random integer values between 0 and 10.
[5 8 9 5 0 0 1 7 6 9 2 4 5 2 4 2 4 7 7 9] 
Array of Random Gaussian Values
An array of random Gaussian values can be generated using the randn() NumPy function.
This function takes a single argument to specify the size of the resulting array. The Gaussian values are drawn from a standard Gaussian distribution; this is a distribution that has a mean of 0.0 and a standard deviation of 1.0.
The example below shows how to generate an array of random Gaussian values.
# generate random Gaussian values from numpy.random import seed from numpy.random import randn # seed random number generator seed(1) # generate some Gaussian values values = randn(10) print(values) 
Running the example generates and prints an array of 10 random values from a standard Gaussian distribution.
[ 1.62434536 0.61175641 0.52817175 1.07296862 0.86540763 2.3015387 1.74481176 0.7612069 0.3190391 0.24937038] 
Values from a standard Gaussian distribution can be scaled by multiplying the value by the standard deviation and adding the mean from the desired scaled distribution. For example:
scaled value = mean + value * stdev 
Where mean and stdev are the mean and standard deviation for the desired scaled Gaussian distribution and value is the randomly generated value from a standard Gaussian distribution.
Shuffle NumPy Array
A NumPy array can be randomly shuffled inplace using the shuffle() NumPy function.
The example below demonstrates how to shuffle a NumPy array.
10 11 
# randomly shuffle a sequence from numpy.random import seed from numpy.random import shuffle # seed random number generator seed(1) # prepare a sequence sequence = [i for i in range(20)] print(sequence) # randomly shuffle the sequence shuffle(sequence) print(sequence) 
Running the example first generates a list of 20 integer values, then shuffles and prints the shuffled array.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] [3, 16, 6, 10, 2, 14, 4, 17, 7, 1, 13, 0, 19, 18, 9, 15, 8, 12, 11, 5] 
Modern Ways of Random Number Generation in NumPy
In newer version of NumPy, you can do random number generation the following way:
10 11 12 13 14 15 16 
import numpy as np rng = np.random.Generator(np.random.PCG64()) rng = np.random.default_rng() # uniform from 0 to 1 value = rng.random() # generate 10 Gaussian random number value = rng.standard_normal(10) # generate 20 random integers between 0 and 10 value = rng.integers(low=0, high=10, size=20) # shuffle a sequence inplace rng.shuffle(sequence) 
The object
rng
is a random number generator. You can create multiple such generators, or use the default one. The idea is to allow you to have multiple independent random number generator so drawing random numbers from one generator would not affect another. This would make your code more robust (because you can mitigate the race condition in parallel algorithms) and allows you to finetune the pseudorandom number generation algorithm.
TL;DR: How Do I Use the randint Function in Python?
The randint function is part of Python’s random module, and it’s used to generate a random integer within a specified range. Here’s a simple example:
import random number = random.randint(1, 10) print(number) # Output: # (A random number between 1 and 10)
In this example, we’re using Python’s
random.randint()
function to generate a random number between 1 and 10. The
import random
line at the beginning is necessary because randint is part of the random module in Python. The function
random.randint(1, 10)
then generates a random integer within the range of 1 and 10.
If you’re interested in learning more about the randint function, including its more advanced uses and potential issues you might encounter, keep reading for a comprehensive exploration.
Table of Contents
 Understanding Python’s randint Function
 Expanding the Range of randint
 Using randint in Loops
 Exploring Alternatives to randint
 Common Issues and Solutions with randint
 Best Practices with randint
 Understanding Random Number Generation in Python
 RealWorld Applications of Python’s randint
 Further Reading: Probability Theory and Statistical Analysis
 Wrapping Up: Python’s randint Function
Summing It Up
In this article, you learned everything about the randint Python function. You also learned something fun, which was creating a lucky draw game that you can enjoy in your free time. You can also tweak that code to make it a bit more complex for a bigger lucky draw game.
It is fascinating to see how one can do so much with Python programming. If you want to learn more about Python’s concepts, you can refer to Simplilearn’s Python Tutorial for Beginners. The tutorial is dedicated to newbies to help them get acquainted with Python’s basics. Once you are done with the basics, you can opt for our Post Graduate Program in Full Stack Web Development course to learn the advanced concepts and excel in Python development.
Have any questions for us? Leave them in the comments section, and our experts will answer them for you ASAP!
Is “randint” a function? Or is it just imported?
Codeacademy automatically adds this code on the top.
from random import randint
What does this function do? I can pass the sections from 7/9 – 9/9 with or without this function. Here is the complete code.
from random import randint board = [] for x in range(0,5): board.append(["O"] * 5) def print_board(board): for row in board: print " ".join(row) def random_row(board): return randint(0, len(board)  1) def random_col(board): return randint(0, len(board[0])  1) ship_row = random_row(board) ship_col = random_col(board) print ship_col print ship_row # Add your code below! guess_row = int(raw_input("Guess Row:")) guess_col = int(raw_input("Guess Col:"))
Wrapping Up: Python’s randint Function
Python’s
randint()
function is a powerful tool in the
random
module, providing a straightforward way to generate random integers within a specified range. From simple applications to more complex scenarios,
randint()
offers a reliable solution for random number generation.
While
randint()
is generally easy to use, common issues include forgetting to import the
random
module and using incorrect range values. These can be easily avoided by following best practices such as always importing necessary modules and ensuring correct parameter values.
Beyond
randint()
, Python offers other methods for random number generation. These include the
random()
and
uniform()
functions in the
random
module, and the
numpy.random.randint()
function in the NumPy module. Each method has its unique advantages and can be more suitable depending on your specific needs.
Random number generation is a fundamental aspect of programming with diverse applications. By mastering Python’s
randint()
function and understanding other random number generation methods, you can harness the power of randomness in your Python projects.
The use of randomness is an important part of the configuration and evaluation of machine learning algorithms.
From the random initialization of weights in an artificial neural network, to the splitting of data into random train and test sets, to the random shuffling of a training dataset in stochastic gradient descent, generating random numbers and harnessing randomness is a required skill.
In this tutorial, you will discover how to generate and work with random numbers in Python.
After completing this tutorial, you will know:
 That randomness can be applied in programs via the use of pseudorandom number generators.
 How to generate random numbers and use randomness via the Python standard library.
 How to generate arrays of random numbers via the NumPy library.
Kickstart your project with my new book Statistics for Machine Learning, including stepbystep tutorials and the Python source code files for all examples.
Let’s get started.
How to Generate Random Numbers in PythonPhoto by Thomas Lipike. Some rights reserved.
RealWorld Applications of Python’s randint
Python’s
randint()
function isn’t just for academic exercises—it has practical applications in realworld scenarios. Let’s explore some of these applications.
Simulations
In simulations,
randint()
can be used to generate random inputs. For example, in a weather simulation,
randint()
could generate random temperatures or wind speeds.
import random random_temperature = random.randint(10, 40) print('Random Temperature:', random_temperature, '°C') # Output: # Random Temperature: (A random number between 10 and 40) °C
In this code, we’re using
randint()
to generate a random temperature between 10 and 40 degrees Celsius.
Games
In games,
randint()
can be used to create unpredictable elements, making the game more exciting. For instance, in a dice game,
randint()
could be used to generate the dice roll.
import random dice_roll = random.randint(1, 6) print('Dice Roll:', dice_roll) # Output: # Dice Roll: (A random number between 1 and 6)
In this code, we’re using
randint()
to simulate a dice roll, generating a random number between 1 and 6.
Data Analysis
In data analysis,
randint()
can be used to generate random samples from a larger dataset. This can ensure a more representative sample and more accurate analysis.
Understanding Random Number Generation in Python
Random number generation is a fundamental concept in programming that has a variety of applications, from game development to data analysis. Python’s
random
module, which includes the
randint()
function, is a powerful tool for generating these random numbers.
The Role of Python’s Random Module
Python’s
random
module provides a suite of functions for generating random numbers. These functions include
randint()
,
random()
,
uniform()
, and many others. Each function generates a random number in a different way or within a different range.
import random random_integer = random.randint(1, 10) random_float = random.random() random_uniform = random.uniform(1.0, 10.0) print(random_integer, random_float, random_uniform) # Output: # (A random integer between 1 and 10, a random float between 0.0 and 1.0, a random float between 1.0 and 10.0)
In this code, we’re using three functions from Python’s
random
module to generate different types of random numbers. Each function provides a unique way to generate random numbers, making the
random
module a versatile tool for random number generation in Python.
The Importance of Randomness in Programming
Randomness plays a crucial role in many areas of programming. For instance, in game development, randomness can be used to create unpredictable gameplay elements. In data analysis, random sampling can help ensure a representative sample of data. By understanding how to generate random numbers in Python, you can harness the power of randomness in your own programming projects.
Discrete distributions¶
The following function generates a discrete distribution.
 random.binomialvariate(n=1, p=0.5)¶

Binomial distribution. Return the number of successes for n independent trials with the probability of success in each trial being p:
Mathematically equivalent to:
sum(random() < p for i in range(n))
The number of trials n should be a nonnegative integer. The probability of success p should be between
0.0 <= p <= 1.0
. The result is an integer in the range
0 <= X <= n
.New in version 3.12.
Sample – Random Numbers
You can also use the sample command to choose several integers from a given range.
By implementing the range command you don’t need to individually write out each number.
from random import sample
numbers = sample(range(1,100) , 5)
print(“Five random numbers between 1 and 100 are:” , *numbers)
Five random numbers between 1 and 100 are: 53 42 11 8 20
Five random numbers between 1 and 100 are: 74 52 51 1 6
Random Samples Task 1 (Frost Comets)
The ice comet from a previous task has broken up into four smaller frosty comets that could pass the Earth anytime from next year to the year 2095.
Print four random years in that range.
Example solutions:
I predict the frost comets will be seen in these years: 2093 2036 2027 2091
I predict the frost comets will be seen in these years: 2076 2033 2053 2085
Random Samples Task 2 (Baby Boy)
Aunt Meredith is having a baby boy.
Create a program that randomly selects 3 male names from a list of 10 possible names.
Example solutions:
Hey Aunt Meredith, how about these names: Charlie Eddie Frank
Hey Aunt Meredith, how about these names: George Harold Bill
Summary
In this tutorial, you discovered how to generate and work with random numbers in Python.
Specifically, you learned:
 That randomness can be applied in programs via the use of pseudorandom number generators.
 How to generate random numbers and use randomness via the Python standard library.
 How to generate arrays of random numbers via the NumPy library.
Do you have any questions?Ask your questions in the comments below and I will do my best to answer.
Importing
Section 5 looks at additional commands that you can import and use from Python’s code libraries.
A library is a collection of different commands that automatically come with Python but are separate from the main file. They can be imported (brought in) to your program by using the import command at the start of your program.
Imagine Python’s library to be similar to an actual library. There are different sections in a real library (such as History, Geography, Reference) and different sections in Python’s library (such as random or time). Each real library has many individual books in each section, just like commands in Python.
randint()
choice()
sample()
shuffle()
random
sleep()
ctime()
strftime()
time
from random import randint
from time import ctime
You can import a specific command from one of Python’s libraries using the from and import commands at the top of your program.
Python3

Program to Demonstrate the ValueError
In this example, we are seeing that if we passes the floating point values as parameters in the randint() function then a ValueError occurs.
Bookkeeping functions¶
 random.seed(a=None, version=2)¶

Initialize the random number generator.
If a is omitted or
None
, the current system time is used. If randomness sources are provided by the operating system, they are used instead of the system time (see the
os.urandom()
function for details on availability).If a is an int, it is used directly.
With version 2 (the default), a
str
,
bytes
, or
bytearray
object gets converted to an
int
and all of its bits are used.With version 1 (provided for reproducing random sequences from older versions of Python), the algorithm for
str
and
bytes
generates a narrower range of seeds.Changed in version 3.2: Moved to the version 2 scheme which uses all of the bits in a string seed.
 random.getstate()¶

Return an object capturing the current internal state of the generator. This object can be passed to
setstate()
to restore the state.
 random.setstate(state)¶

state should have been obtained from a previous call to
getstate()
, and
setstate()
restores the internal state of the generator to what it was at the time
getstate()
was called.
What are the Applications of Randint Python Function?
Since the Python randint() function generates a pseudorandom integer, it is usually helpful in gaming and lottery applications. For instance, let’s say a participant gets three chances to guess the following random number generated within a range. If the person gets it correct within the three attempts, he wins, or else loses. Let’s simulate this situation using the randint Python function in the example below.
Example: Creating a Lucky Draw Game with the randint() Function
In the below code, you will generate a random number between 1 and 20 three times. You will then accept input from the user and check if the guess is correct and wins. Let’s begin with our example.
# importing randint function
from random import randint
# Function to generate new random integer
def random_generator():
return randint(1, 20)
# Function to take input from user and show results
def your_guess():
# calling function to generate random numbers
rand_number = random_generator()
# defining the number of
# guesses the user gets
remaining_gus = 3
# Setting wincondition checker flagship variable
flagship = 0
# Using loop to provide only three chances
while remaining_gus > 0:
# Taking user input
guess_num = int(input(“What’s your guess?\n”))
# checking if the guess is correct
if guess_num == rand_number
# setting flagship 1 for correct guess to
# break loop
flagship = 1
break
else:
# printing the failure message
print(“Oops, you missed!”)
# Decrementing guesses left
remaining_gus = 1
# your_guess function returns True if wincondition
# is satisfied
if flagship == 1:
return True
# else returns False
else:
return False
# Final output code to decide win or lose
if __name__ == ‘__main__’:
if your_guess() is True:
print(“Wow, you hit the bull’s eye!”)
else :
print(“Sorry, better luck next time!”)
Output:
Second attempt output:
Well, as it is evident, you could not get it correct in the first game. But in the second game, you hit the bull’s eye in the very first attempt. Copypaste the code in any Python compiler, and you too can enjoy the game. You can compete with your friends and family members, and make a day out of it.
Using randint in Loops
One of the powerful ways to use
randint()
is within loops. This allows you to generate multiple random numbers at once. For instance, if you need to generate a list of 5 random numbers between 1 and 10, you can use a for loop with
randint()
:
import random random_numbers = [random.randint(1, 10) for _ in range(5)] print(random_numbers) # Output: # (A list of 5 random numbers between 1 and 10)
In this code, we’re using a for loop to generate a list of 5 random numbers. The
random.randint(1, 10)
function is called 5 times, once for each iteration of the loop, generating a new random number each time. The result is a list of 5 random integers.
These examples demonstrate how you can use Python’s
randint()
function in more complex ways to suit your needs. By adjusting the range and using loops, you can generate a variety of random number sequences.
Choice – Random Word
Rather than just numbers, we can also randomly generate characters or strings from a specified range by using the choice command.
You must first import the choice command from the random library. Choice works well with a list of values, which require square brackets and commas separating each word.
Below is a program that randomly chooses from a list of animals:
from random import choice
animals = [“cat” , “dog” , “horse” , “cow”]
print(“A random animal is” , choice(animals))
A random animal is horse
What Happens in Case of Multiple randint() Method Call?
You have seen that when you call the randint Python function; it generates and returns a random integer from the specified range. But what if you call it multiple times? Can it return the same value twice? If not, what happens if the number of calls is more than the available range of values? Let’s get all these queries answered.
Example: Calling the Randint Python Function Multiple Times
In this example, you will keep the available range larger. Let’s see the output.
import random
init=1
end=50
for x in range(5):
print(random.randint(init, end))
Output:
As you can see in the output, the randint() function could still give different random values. Now, let’s cut short the available range and see what happens.
import random
init=1
end=10
for x in range(5):
print(random.randint(init, end))
Output:
Since the range was shorter and the number of calls was still 5, the randint Python function gave a repeated value: 5. Thus, the randint() function can provide the same number twice or even more times. There are also chances that you might get a repeated value, even if the available range is more extensive.
Conclusion
 randint() function is used to generate the random integers between the two given numbers passed as parameters.
 Randint is an inbuilt function of random library in python. So we have to import the random library at the start of our code to generate random numbers.

randint function returns:
 ValueError, when floating point values are passed as parameters.
 TypeErrorwhen anything other than numeric values is passed as parameters.
The random module in Python allows you to generate pseudorandom variables. The module provides various methods to get the random variables, one of which is the randint method. The randint Python function is a builtin method that lets you generate random integers using the random module.
Notes on Reproducibility¶
Sometimes it is useful to be able to reproduce the sequences given by a pseudorandom number generator. By reusing a seed value, the same sequence should be reproducible from run to run as long as multiple threads are not running.
Most of the random module’s algorithms and seeding functions are subject to change across Python versions, but two aspects are guaranteed not to change:

If a new seeding method is added, then a backward compatible seeder will be offered.

The generator’s
random()
method will continue to produce the same sequence when the compatible seeder is given the same seed.
Parameters Used in Randint Python Function
As you can see in the syntax, the Python randint() function accepts two parameters, which are:
 start: It is a required parameter that accepts integer value and determines the starting range from which it will generate the random integer.
 end: It is a required parameter that accepts integer value and defines the ending of the range from which it will generate the random integer.
Popular free courses

Free Course
Learn SQL
In this SQL course, you’ll learn how to manage large datasets and analyze real data using the standard data management language.Beginner friendly,4 LessonsLanguage Fluency

Free Course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner friendly,11 LessonsLanguage Fluency

Free Course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner friendly,6 LessonsLanguage Fluency
The use of randomness is an important part of the configuration and evaluation of machine learning algorithms.
From the random initialization of weights in an artificial neural network, to the splitting of data into random train and test sets, to the random shuffling of a training dataset in stochastic gradient descent, generating random numbers and harnessing randomness is a required skill.
In this tutorial, you will discover how to generate and work with random numbers in Python.
After completing this tutorial, you will know:
 That randomness can be applied in programs via the use of pseudorandom number generators.
 How to generate random numbers and use randomness via the Python standard library.
 How to generate arrays of random numbers via the NumPy library.
Kickstart your project with my new book Statistics for Machine Learning, including stepbystep tutorials and the Python source code files for all examples.
Let’s get started.
How to Generate Random Numbers in PythonPhoto by Thomas Lipike. Some rights reserved.
Answer 55c1f9dbe0a300455c000072
Hi, @Takeshi Travis Sugiyama,
randint
is a function that is part of the
random
module.
The official Python documentation on it is at random.randint(a, b). It returns a pseudorandom integer between and , inclusive.
You must
import
the function in some manner, in order to use it. The statement …
from random import randint
… enables you to use the name
randint
to call the function.
If, instead you had …
import random
… you would need to use dot notation to specify the name of the module, in connection with the name of the function, in order to call it, for example …
return random.randint(0, len(board)  1)
If you managed to pass without using the
randint
function at all, congratulations :). But, of course the game is less interesting if it does not choose a random location for the battleship.
If you passed with code that used the
randint
function, but after your having removed the
import
statement, it was because Codecademy remembers names defined by previous submissions of exercises in the same section, during a given session. This is a possible source of confusion, as it can cause code to be accepted when it is, in fact, incomplete. To make sure your code is actually valid, you can refresh the page and submit the code again.
Python3

Output
Pick your number to enter the lucky draw
8
Wrong Guess!!
Pick your number to enter the lucky draw
9
Wrong Guess!!
Pick your number to enter the lucky draw
0
Congrats!! You Win.
Don’t miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.
Dive into the future of technology – explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Last Updated :
30 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments