Python code for the coin toss issues

64,642

Solution 1

import random

total_heads = 0
total_tails = 0
count = 0


while count < 100:

    coin = random.randint(1, 2)

    if coin == 1:
        print("Heads!\n")
        total_heads += 1
        count += 1

    elif coin == 2:
        print("Tails!\n")
        total_tails += 1
        count += 1

print("\nOkay, you flipped heads", total_heads, "times ")
print("\nand you flipped tails", total_tails, "times ")

Solution 2

import random

samples = [ random.randint(1, 2) for i in range(100) ]
heads = samples.count(1)
tails = samples.count(2)

for s in samples:
    msg = 'Heads' if s==1 else 'Tails'
    print msg

print "Heads count=%d, Tails count=%d" % (heads, tails)

Solution 3

You have a variable for the number of tries, which allows you to print that at the end, so just use the same approach for the number of heads and tails. Create a heads and tails variable outside the loop, increment inside the relevant if coin == X block, then print the results at the end.

Solution 4

# Please make sure to import random.

import random

# Create a list to store the results of the for loop; number of tosses are limited by range() and the returned values are limited by random.choice().

tossed = [random.choice(["heads", "tails"]) for toss in range(100)]

# Use .count() and .format() to calculate and substitutes the values in your output string.

print("There are {} heads and {} tails.".format(tossed.count("heads"), tossed.count("tails")))

Solution 5

Keep a running track of the number of heads:

import random
tries = 0
heads = 0
while tries < 100:
    tries += 1
    coin = random.randint(1, 2)
    if coin == 1:
        heads += 1
        print('Heads')
    if coin == 2:
        print ('Tails')
total = tries
print('Total heads '.format(heads))
print('Total tails '.format(tries - heads))
print(total)
Share:
64,642
Ru1138
Author by

Ru1138

Updated on February 09, 2020

Comments

  • Ru1138
    Ru1138 over 4 years

    I've been writing a program in python that simulates 100 coin tosses and gives the total number of tosses. The problem is that I also want to print the total number of heads and tails.

    Here's my code:

    import random
    tries = 0
    while tries < 100:
        tries += 1
        coin = random.randint(1, 2)
        if coin == 1:
            print('Heads')
        if coin == 2:
            print ('Tails')
    total = tries
    print(total)
    

    I've been racking my brain for a solution and so far I have nothing. Is there any way to get the number of heads and tails printed in addition to the total number of tosses?

    • Fredrik Pihl
      Fredrik Pihl almost 13 years
      howabout adding adding a counter in each of the if-cases (one for heads and one for tails)?
    • david van brink
      david van brink almost 13 years
      Same as counting tries... but only count when it's printing heads. Something like heads += 1 will be the ticket :-)
    • Chris Cunningham
      Chris Cunningham almost 13 years
      Look at what the "tries" variable does and try to replicate that with a "heads" and a "tails" variable. But don't do heads+=1 every time ... You can figure it out!
  • Ru1138
    Ru1138 almost 13 years
    P'sao's answer had the code, but you had the explanation. My thanks go out to you as well as P'sao.
  • Karl Knechtel
    Karl Knechtel almost 13 years
    +1 this is much closer to how we normally do things in Python. Free your mind; don't try to think about things a step at a time, because as you've proven to yourself, it's not that easy. Think about what you want accomplished: "I want a sequence of 100 coin flips; I want an output of 'Heads' or 'Tails' for each one in order; I want to display a count of the heads and of the tails".
  • cha0site
    cha0site over 12 years
    You didn't actually answer the question - you're not counting the number of head or tail tosses.
  • yurisich
    yurisich over 12 years
    I hope the op tries building this a couple of times. A very good introduction to comprehensions right here (line 3).
  • hughdbrown
    hughdbrown over 12 years
    A couple of things. (1) The loop counter i is not read, so you could write: samples = [random.randint(1, 2) for _ in range(100)]. (2) You can use a lookup table for results: messages = {1: "Heads", 2: "Tails"} for s in samples: print messages[s] (3) might be a good place for enumerate: for i, s in enumerate(samples): print i, messages[s]
  • hughdbrown
    hughdbrown over 12 years
    Hmmm. I didn't know about random.getrandombits.
  • hughdbrown
    hughdbrown over 12 years
    Yes, this is the minimal change to the OP's code. Not really idiomatic python, though.
  • hughdbrown
    hughdbrown over 12 years
    @cha0site I don't understand your interpretation of the question. This code counts the number of heads and tails. Run the code and see.
  • harmonica141
    harmonica141 over 4 years
    This is almost a c/p answer, OP's question has been answered.
  • johannchopin
    johannchopin over 4 years
    Maybe you can add some explanation to it rather than just post a block of code
  • Edward
    Edward over 4 years
    my apologies. I have added comments to my code to explain my logic. hope it helps.
  • Edward
    Edward over 4 years
    the code above is to display heads or tails in a 100 times coin flip. It is added with counter for both heads and tails so that out of 100 times coin flip, i am able to know how many are heads or tails. lastly to print the result to display count.