Member-only story
Simulating randomness using Python’s random module
Randomness exists everywhere. In this tutorial, we will learn how to simulate randomness using Python’s random module. Using a few common examples that you have probably come across in your high school, simulation of randomness using Python is explained here.
Simulate flipping of a coin
The simplest random process that probably comes first in our mind is the flipping of an unbiased coin. The outcome will be either head (H) or tail (T). To simulate this in Python, we can use the random library of Python.
import randomrandom.choice(["H", "T"])
This will generate either ‘H’ or ‘T’.
Instead of using a list of strings, we can use a list of numbers as follows:
random.choice([0, 1])
This will generate either 0 or 1.
Simulate rolling of a die
This is one of the most common random experiment that we have come across in our high school mathematics class. In general, a die has six faces starting from 1 to 6. So, the output will be any random number in [1, 2, 3, 4, 5, 6].
random.choice([1,2,3,4,5,6])