Python Coin Toss
Asked Answered
P

14

15

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")))
Palaeontology answered 14/2, 2013 at 19:27 Comment(3)
There are better options in random but I presume you have to solve the problem long hand so to speak.Nubbly
Can you give some more information? "it isn't working at all" isn't very descriptive. What specifically is the problem?Macedonian
The program simply prints either 'Tails' or 'Heads' and 0 or 1Palaeontology
U
16

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().

Upstart answered 14/2, 2013 at 19:32 Comment(0)
C
8

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.

Comte answered 14/2, 2013 at 19:30 Comment(0)
S
5

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
Somnambulate answered 7/10, 2013 at 22:41 Comment(0)
B
3

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
Backhander answered 14/2, 2013 at 19:58 Comment(0)
T
2
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)

Terryn answered 3/5, 2018 at 1:54 Comment(0)
M
1

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))
Melanoid answered 13/8, 2019 at 18:45 Comment(0)
R
1

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"))

A more concise approach

However, if you're looking for a more concise solution, you can use a list comprehension. There's only one other answer that has a list comprehension, but you can embed the mapping from {0, 1} to {"Heads", "Tails"} using one, rather than two, list comprehensions:

def coinToss():
    number = int(input("Number of times to flip coin: "))
    recordList = ["Heads" if random.randint(0, 1) else "Tails" for _ in range(number)]
    print(recordList)
    print(recordList.count("Tails"), recordList.count("Heads"))
Report answered 3/3, 2022 at 5:13 Comment(0)
O
0

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')
Oxfordshire answered 18/1, 2020 at 8:55 Comment(0)
P
0

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))
Postoperative answered 3/1, 2021 at 10:40 Comment(0)
S
0
#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))
    
Shakiashaking answered 14/4, 2021 at 15:47 Comment(0)
H
-1
import random

def coinToss(number):
    heads = 0
    tails = 0
    for flip in range(number):
        coinFlip = random.choice([1, 2])

        if coinFlip == 1:
            print("Heads")
            recordList.append("Heads")
        else:
            print("Tails")
            recordList.append("Tails")

number = input("Number of times to flip coin: ")
recordList = []
if type(number) == str and len(number)>0:
    coinToss(int(number))
    print("Heads:", str(recordList.count("Heads")) , "Tails:",str(recordList.count("Tails")))
Haileyhailfellowwellmet answered 16/12, 2019 at 15:6 Comment(0)
B
-1

All Possibilities in Coin Toss for N number of Coins

def Possible(n, a):
    if n >= 1:
        Possible(n // 2, a)
    z = n % 2
    z = "H" if z == 0 else "T"
    a.append(z)
    return a


def Comb(val):
    for b in range(2 ** N):
        A = Possible(b, [])
        R = N - len(A)
        c = []
        for x in range(R):
            c.append("H")
        Temp = (c + A)
        if len(Temp) > N:
            val.append(Temp[abs(R):])
        else:
            val.append(Temp)
    return val


N = int(input())
for c in Comb([]):
    print(c)
Biophysics answered 20/9, 2021 at 13:32 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Interfluent
T
-1
heads = 1
tails = 0 

input("choose 'heads' or 'tails'. ").upper()

random_side = random.randint(0, 1)

if random_side == 1:
    print("heads you win")
else:
    print("sorry you lose ")
Tagmemic answered 31/10, 2021 at 18:58 Comment(1)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: stackoverflow.com/help/how-to-answer . Good luck 🙂Jarlath
W
-1

None of the other solutions worked for me. This is what I did and it worked:

import random

 random_side = random.randint(0, 1)
  if random_side == 1:
    print("Heads")
  else:
   print("Tails")
Warta answered 25/3 at 5:32 Comment(1)
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewExchequer

© 2022 - 2024 — McMap. All rights reserved.