How To Code A Fair Coin Flip In Python — Regina Of Tech | by ReginaOfTech | Towards Data Science

To master anything, you need to start at the beginning, understanding the basics. Coding a fair coin flip is kind of a right of passage when it comes to python. It seems like a simple project, but it can be done in many different ways. You may even get an insight into your coding habits. Being able to critique your code is a critical programmer skill, but that is another post. Let’s get into what you clicked for, coding a fair coin flip in python.
Before we start tapping away, creating a program that makes a computer do a mundane task such as flipping a coin, let’s fly up 10,000 feet and get our bearings. Programmers have an amazing amount of creative freedom (well depending on your (micro)manager, I empathize with you if you are in that boat ❤), you can start to lose focus on what the main focus is on a project. Yes, even with a simple project like this, habits are made in and out of the public eye. Your standard is only as high as when no one is looking.
Ok. Now that we have a bird’s eye view of our project lets dissect it. We know that we will be doing a fair coin flip. A coin is made up of two halves, head and tails. Since ‘fair’ is used in the project description we know that the probability will be a 50% chance of getting either side. If the description mentioned biased or weighted coin then the probability would be adjusted.
How are we going to simulate a coin flip? We can’t give the computer a bitcoin and tell it to flip it. Since we are using python, a mathematically focused language, we will use probability. Specifically numpy’s binomial distribution, np.random.binomial(n,p). This is a method in the random class and it takes in the number of trials (n) and the probability of the event occurring (p). Binomial distribution, as its name suggests, can perform a ‘coin flip’ of two events happening. The call returns a 0 or 1 to represent one of the two events. Here is the equation that it uses:
p is the probability, n is the number of trials ran, and N is the number of successes. We know now that for the binomial distribution to work we need two variables, n and p.
This opens the question, do we want to see each flip and track it or are we satisfied with just the number of times a positive (1) event occurred? I’m on board with seeing an array of events, just for fun. So we will need an array to store the results in. Thank goodness numpy can do all of that!
Let’s come back down to the ground and get coding.
First things first, we need to import numpy.
import numpy as np
Next, we’ll create the n and p variables. We know that we will need those since we will be using np.random.binomial and that requires the number of trials and the probability.
'''Main Area'''#probability of heads vs. tails. This can be changed.probability = .5#num of flips required. This can be changed.n = 10
In my code, I like to mark where the main area is for easy searching just in case there are several methods created in that program. Marking any variables that can be safely changed without any negative effects is a great practice to get into as well.
We also know that we will need to initiate an array to store the flips. Using np.arange will create an array with 10 elements filled with 0 to 9 value in ascending order.
#initiate arrayfullResults = np.arange(n)
This is the point where we can go down two paths. One that requires us to create a function that does the ‘flip’ or does the ‘flip’ in the for loop. Since we are about code re-usability we will create a function that houses the binomial distribution. This will allow for easy access if we decide to build upon the program in the future.
With that decision, let’s create the method. We will call it coinFlip and it will need to take in the probability for the events. It will return the result from the binomial. Be sure to place this before the main area. The program needs to define it before it can be used.
def coinFlip(p):        #perform the binomial distribution (returns 0 or 1)        result = np.random.binomial(1,p)            #return flip to be added to numpy array        return result
As you can see, the number of trials will be set to 1. This will return only a 0 or 1, false or true. Now the for loop can be created that will call coinFlip.
#perform desired numbered of flips at required probability set abovefor i in range(0, n):        fullResults[i] = coinFlip(probability)        i+=1
For loops are basic code structures, but just in case lets walk through what is happening. The i in the header will be the index that controls whether or not the loop is done again. range(0,n) are the values that i can be. We use n so that we do not exceed our array size. When the program can step into the loop the coinFlip that we created is called and the result is saved to the element in our array. The index, i, is then incremented.
We are almost done. The final step will be to count and print the results. This part is pretty easy. For the print part, we will print the probability that was used for verification that the proper one was used, along with the fullResult array. Numpy has many different functions that are targeted towards arrays. We will be using np.count_nonzero() which will iterate through the array and count the number of occurrences of the number that we give it. In this case, we will be checking for the number of times 1 and 0 occur.
#print resultsprint("probability is set to ", probability)print("Tails = 0, Heads = 1: ", fullResults)#Total up heads and tails for easy user experience print("Head Count: ", np.count_nonzero(fullResults == 1))print("Tail Count: ", np.count_nonzero(fullResults == 0))
That’s it! We have created a program that will simulate a fair coin flip. Here is what the code should look like:
import numpy as npdef coinFlip(p):        #perform the binomial distribution (returns 0 or 1)        result = np.random.binomial(1,p)#return flip to be added to numpy array        return result'''Main Area'''#probability of heads vs. tails. This can be changed.probability = .5#num of flips required. This can be changed.n = 10#initiate arrayfullResults = np.arange(n)#perform desired numbered of flips at required probability set abovefor i in range(0, n):        fullResults[i] = coinFlip(probability)        i+=1#print resultsprint("probability is set to ", probability)print("Tails = 0, Heads = 1: ", fullResults)#Total up heads and tails for easy user experience print("Head Count: ", np.count_nonzero(fullResults == 1))print("Tail Count: ", np.count_nonzero(fullResults == 0))
That was fun! Doing simple projects like a fair coin flip is a great way to understand a library such as numpy. Numpy is a powerful library and can do plenty more than just simulating a coin flip and creating an array. If you are interested in learning more, check out Learn The Basics Of Pythons Numpy. The article will give a broader understanding of numpy.
Thank you for reading!
Until we learn again,
Originally published on https://reginaoftech.com