Python Random - Flip a Coin
Python Flip a Coin
In this tutorial, we shall learn to write a function, that randomly returns True or False corresponding to a Head or Tail for the experiment of flipping a coin.
To randomly select on of the two possible outcomes, you can use random.choice() function, with the two outcomes passed as list elements. Or you can use random.random() function that returns a floating point and decide one of the two possible outcomes based on the output range.
Programs
1. Python function to Flip a coin
In this example, we shall write a function, called flipCoin(). This function returns True or False randomly with each call.
As already mentioned in the introduction, we shall call random.choice() with the list [True, False]
passed as argument.
Python Program
import random
import string
def flipCoin():
return random.choice([True,False])
for i in range(0,5):
print(flipCoin())
We have called flipCoin() function multiple times using a Python For Loop to demonstrate the randomness of the returned value.
Output
False
True
True
False
True
Please note that there is no control on the number of True
s or False
s returned for a limited function calls of flipCoin().
As the number of times you flip a coin tend to a very large number or infinity, the probability of Head or False tend to 0.5
.
2. Flip a coin experiment using random.random()
random.random() function returns a floating value in the range (0,1). You can decide that the flipping a coin results in Head if random.random() returns a value in between 0 and 0.5, and a Tail if random.random() returns a value between 0.5 and 1.
In this example, we shall use random.random() function to programmatically implement the experiment of flipping a coin.
Python Program
import random
import string
def flipCoin():
f = random.random()
return True if f<0.5 else False
for i in range(0,5):
print(flipCoin())
Output
True
False
False
True
False
Summary
In this tutorial of Python Examples, we learned how to use random package to programmatically implement the experiment: Flip a Coin.