7

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?

julianfperez
  • 1,616
  • 5
  • 35
  • 66
Ru1138
  • 151
  • 1
  • 2
  • 12

11 Answers11

15
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)
pajton
  • 14,670
  • 6
  • 50
  • 63
  • 1
    +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". – Karl Knechtel Jun 27 '11 at 00:49
  • I hope the op tries building this a couple of times. A very good introduction to comprehensions right here (line 3). – Droogans Jan 28 '12 at 00:00
  • 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 Jan 28 '12 at 14:21
4

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.

bradley.ayers
  • 33,409
  • 13
  • 84
  • 94
  • P'sao's answer had the code, but you had the explanation. My thanks go out to you as well as P'sao. – Ru1138 Jun 26 '11 at 22:33
3
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 ")
Community
  • 1
  • 1
1

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)
Ted Hopp
  • 222,293
  • 47
  • 371
  • 489
1
import random
tries = 0
heads=0
tails=0
while tries < 100:
    tries += 1
    coin = random.randint(1, 2)
    if coin == 1:
        print('Heads')
        heads+=1
    if coin == 2:
        print ('Tails')
        tails+=1
total = tries
print(total)
print tails
print heads
P'sao
  • 2,416
  • 10
  • 35
  • 46
1
# 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")))
jason
  • 21
  • 3
  • You didn't actually answer the question - you're not counting the number of head or tail tosses. – cha0site Jan 27 '12 at 23:49
  • @cha0site I don't understand your interpretation of the question. This code counts the number of heads and tails. Run the code and see. – hughdbrown Jan 28 '12 at 14:27
1
tosses = 100
heads = sum(random.randint(0, 1) for toss in range(tosses))
tails = tosses - heads
Peter Wood
  • 21,348
  • 4
  • 53
  • 90
1

You could use random.getrandbits() to generate all 100 random bits at once:

import random

N = 100
# get N random bits; convert them to binary string; pad with zeros if necessary
bits = "{1:>0{0}}".format(N, bin(random.getrandbits(N))[2:])
# print results
print('{total} {heads} {tails}'.format(
    total=len(bits), heads=bits.count('0'), tails=bits.count('1')))

Output

100 45 55
jfs
  • 346,887
  • 152
  • 868
  • 1,518
0

I ended up with this.

import random

flips = 0
heads = 0
tails = 0

while flips < 100:
    flips += 1

    coin = random.randint(1, 2)
    if coin == 1:
       print("Heads")
       heads += 1

    else:
       print("Tails")
       tails += 1

total = flips

print(total, "total flips.")
print("With a total of,", heads, "heads and", tails, "tails.")
0

Here is my code. Hope it will help.

import random

coin = random.randint (1, 2)

tries = 0
heads = 0
tails = 0

while tries != 100:

if coin == 1:
    print ("Heads ")
    heads += 1
    tries += 1
    coin = random.randint(1, 2)

elif coin == 2:
    print ("Tails ")
    tails += 1
    tries += 1
    coin = random.randint(1, 2)
else:
    print ("WTF")

print ("Heads = ", heads)
print ("Tails = ", tails)
0
import random

print("coin flip begins for 100 times")

tails = 0
heads = 0
count = 0
while count < 100: #to flip not more than 100 times
count += 1
result = random.randint(1,2) #result can only be 1 or 2.

    if result == 1: # result 1 is for heads
        print("heads")
    elif result == 2: # result 2 is for tails
        print("tails")
    if result == 1:
        heads +=1 #this is the heads counter.
    if result == 2:
        tails +=1 #this is the tails counter.
# with all 3 being the count, heads and tails counters,
# i can instruct the coin flip not to exceed 100 times, of the 100 flips 
# with heads and tails counter, 
# I now have data to display how of the flips are heads or tails out of 100.
print("completed 100 flips") #just to say 100 flips done.
print("total tails is", tails) #displayed from if result == 2..... tails +=1
print("total heads is", heads)
Edward
  • 1
  • 1
  • 1
    Maybe you can add some explanation to it rather than just post a block of code – johannchopin Feb 07 '20 at 18:03
  • my apologies. I have added comments to my code to explain my logic. hope it helps. – Edward Feb 08 '20 at 15:58
  • 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. – Edward Feb 08 '20 at 16:06