What is Randomization in Python – Explained with Coin Flip Example

What is Randomization?
Randomization is to make something unpredictable and with no rules. But in real-time making a program unpredictable is something very difficult to achieve
Randomization is very important if we want to create a computing program that is unpredictable.
One good example is Games 🙂
How Python Implements Randomization
Python uses “Mersenne Twister” Algorithm to generate the random behavior. It’s a pseudorandom number generator, which generates a random number.
For More details check the wiki link
In Python, A Module was created already to use this “pseudorandom number generator” which is called a “random module“
Let’s see some examples:
To use the random module, We need to import it First as below
import random print(randint(0,10))
Output:
2 6 9
The above code will generate a random number between 0 – 10 (0 and 10 included)
Let’s use the above module in action. We can create a simple coin flip program to generate random output (Either Heads or Tails)
import random random_number=random.randint(0,1) if (random_number==0): print("Heads") else: print("Tails")
Explanation
– We have used the “random module” to provide either 0 or 1 as an output
– 0 and 1 will be assigned as Head and tails
– So each time you execute the program, You will see either heads or tails and it is unpredictable
Check here for more Python learning series posts
Good Luck with your Learning.