Flipping a Coin in Python

Photo by Andriyko Podilnyk on Unsplash

There are many ways to create a coin flipper, but there is an elegant way, using the singleton design pattern. In brief, singletons mean that you instantiate a single object from a class at one time, in this case, its heads or tails.


from enum import Enum, auto
import random

Enum: is our data type.
Auto: assign value starting from 1.
Random: is a pseudo-random number generator.

Create a coin:

class Coin(Enum):
heads = auto()
tails = auto()
list(Coin) #=> [<Coin.heads: 1>, <Coin.tails: 2>]

The class coin has two variables (heads and tails).
Heads have the value 1, while tails have the value 2.

Creating the Flip Function:

def flip() -> Coin:
return random.choice(list(Coin))
flip() #=> <Coin.heads: 1>

The function flip utilizes the choice method from the random library.
Create a list of flips.


heads_list = [flip() for _ in range(1000)]
heads_list.count(Coin.heads) #=> 514
heads_list.count(Coin.tails) #=> 486

Using a comprehension list of 1000 flips.
We get the following count; the values are almost 50–50 because the choice function produces a uniform distribution (where each value is equally likely to be picked).

Use enum to create a singleton when you have a list of defined constants, and you want to draw a single object.




Reject the null hypothesis

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Complete Web Developer Course 2.0

Taraxa Testnet Weekly Update.

Generating Code from Xcode Configurations

>Hello World! Source code is open. Bug bounty and audits.

A short note about REST

Install OpenCV 4.0.1 from Source on MacOS with Anaconda Python 3.7 to Use SIFT and SURF

EP10: Writing code at the age of 12 to now creating applications to offering easy use of satellite…

Introduction to Kotlin Coroutines

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mansoor Aldosari

Mansoor Aldosari

Reject the null hypothesis

More from Medium

Top 10 mistakes that people do while writing the python code

Python Programming Language

HARMAN Python Training Day4

Datatypes of python