Python Coin Toss

I am VERY new to Python and I have to create a game that simulates flipping a coin and ask the user to enter the number of times that a coin should be tossed. Based on that response the program has to choose a random number that is either 0 or 1 (and decide which represents “heads” and which represents “tails”) for that specified number of times. Count the number of “heads” and the number of “tails” produced, and present the following information to the user: a list consisting of the simulated coin tosses, and a summary of the number of heads and the number of tails produced. For example, if a user enters 5, the coin toss simulation may result in [‘heads’, ‘tails’, ‘tails’, ‘heads’, ‘heads’]. The program should print something like the following: “ [‘heads’, ‘tails’, ‘tails’, ‘heads’, ‘heads’]

This is what I have so far, and it isn't working at all...

import random

def coinToss():
    number = input("Number of times to flip coin: ")
    recordList = []
    heads = 0
    tails = 0
    flip = random.randint(0, 1)
    if (flip == 0):
        print("Heads")
        recordList.append("Heads")
    else:
        print("Tails")
        recordList.append("Tails")
    print(str(recordList))
    print(str(recordList.count("Heads")) + str(recordList.count("Tails")))
3

13 Answers

You need a loop to do this. I suggest a for loop:

import random
def coinToss():
    number = input("Number of times to flip coin: ")
    recordList = []
    heads = 0
    tails = 0
    for amount in range(number):
         flip = random.randint(0, 1)
         if (flip == 0):
              print("Heads")
              recordList.append("Heads")
         else:
              print("Tails")
              recordList.append("Tails")
    print(str(recordList))
    print(str(recordList.count("Heads")) + str(recordList.count("Tails")))

I suggest you read this on for loops.

Also, you could pass number as a parameter to the function:

import random
def coinToss(number):
    recordList, heads, tails = [], 0, 0 # multiple assignment
    for i in range(number): # do this 'number' amount of times
         flip = random.randint(0, 1)
         if (flip == 0):
              print("Heads")
              recordList.append("Heads")
         else:
              print("Tails")
              recordList.append("Tails")
    print(str(recordList))
    print(str(recordList.count("Heads")) + str(recordList.count("Tails")))

Then, you need to call the function in the end: coinToss().

You are nearly there:

1) You need to call the function:

coinToss()

2) You need to set up a loop to call random.randint() repeatedly.

I'd go with something along the lines of:

from random import randint
num = input('Number of times to flip coin: ')
flips = [randint(0,1) for r in range(num)]
results = []
for object in flips:
        if object == 0:
            results.append('Heads')
        elif object == 1:
            results.append('Tails')
print results

This is possibly more pythonic, although not everyone likes list comprehensions.

import random

def tossCoin(numFlips):      
    flips= ['Heads' if x==1 else 'Tails' for x in [random.randint(0,1) for x in range(numflips)]]
    heads=sum([x=='Heads' for x in flips])
    tails=numFlips-heads
import random
import time



flips = 0
heads = "Heads"
tails = "Tails"

heads_and_tails = [(heads),
                   (tails)]
while input("Do you want to coin flip? [y|n]") == 'y':
    print(random.choice(heads_and_tails))
    time.sleep(.5)
    flips += 1


else:
    print("You flipped the coin",flips,"times")
    print("Good bye")

You could try this, i have it so it asks you if you want to flip the coin then when you say no or n it tells you how many times you flipped the coin. (this is in python 3.5)

Create a list with two elements head and tail, and use choice() from random to get the coin flip result. To get the count of how many times head or tail came, append the count to a list and then use Counter(list_name) from collections. Use uin() to call

##coin flip
import random
import collections
def tos():
    a=['head','tail']
    return(random.choice(a))
def uin():
    y=[]
    x=input("how many times you want to flip the coin: ")
    for i in range(int(x)):
        y.append(tos())
    print(collections.Counter(y))

Instead of all that, you can do like this:

import random
options = ['Heads' , 'Tails']
number = int(input('no.of times to flip a coin : ')
for amount in range(number):
   heads_or_tails = random.choice(options)
   print(f" it's {heads_or_tails}")
print()
print('end')

I did it like this. Probably not the best and most efficient way, but hey now you have different options to choose from. I did the loop 10000 times because that was stated in the exercise.

#Coinflip program
import random

numberOfStreaks = 0
emptyArray = []
for experimentNumber in range(100):
#Code here that creates a list of 100 heads or tails values
headsCount = 0
tailsCount = 0
#print(experimentNumber)
for i in range(100):
    if random.randint(0, 1) == 0:
        emptyArray.append('H')
        headsCount +=1
    else:
        emptyArray.append('T')
        tailsCount += 1   

#Code here that checks if the list contains a streak of either heads or tails of 6 in a row
heads = 0
tails = 0
headsStreakOfSix = 0
tailsStreakofSix = 0

for i in emptyArray:
    if i == 'H':
        heads +=1
        tails = 0
        if heads == 6:
            headsStreakOfSix += 1
            numberOfStreaks +=1
            
    if i == 'T':
        tails +=1
        heads = 0
        if tails == 6:
            tailsStreakofSix += 1
            numberOfStreaks +=1
            
#print('\n' + str(headsStreakOfSix))
#print('\n' + str(tailsStreakofSix))
#print('\n' + str(numberOfStreaks))
print('\nChance of streak: %s%%' % (numberOfStreaks / 10000))
#program to toss the coin as per user wish and count number of heads and tails
import random
toss=int(input("Enter number of times you want to toss the coin"))
tail=0
head=0
for i in range(toss):
    val=random.randint(0,1)
    if(val==0):
        print("Tails")
        tail=tail+1
    else:
        print("Heads")
        head=head+1
print("The total number of tails is {} and head is {} while tossing the coin {} times".format(tail,head,toss))
    
0

Fixing the immediate issues

The highest voted answer doesn't actually run, because it passes a string into range() (as opposed to an int).

Here's a solution which fixes two issues: the range() issue just mentioned, and the fact that the calls to str() in the print() statements on the last two lines can be made redundant. This snippet was written to modify the original code as little as possible.

def coinToss():
    number = int(input("Number of times to flip coin: "))
    recordList = []
    heads = 0
    tails = 0
    for _ in range(number):
        flip = random.randint(0, 1)
        if (flip == 0):
            recordList.append("Heads")
        else:
            recordList.append("Tails")
    print(recordList)
    print(recordList.count("Tails"), recordList.count("Heads"))

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.