While loops and if/else


#1



I have no idea where to start. Any help would be much appreciated.
Here is the problem:

Write a program that flips a coin 100 times and then tells you the number of heads and tails.


Replace this line with your code.


#2

declare two variable, head and tail, and assign them a value of zero (we use this variable to keep track of how many heads and tails we have)

write a loop

figure out a way to generate a random number so we can get head or tails


#3

Does this work?

import random

# set the coin
headsCount, tailsCount, count = 0, 0, 0

# the loop
count = 0
while count<100: 
    coin = random.randrange(2)
    if coin == 0:
         headsCount += 1
    else:
        tailsCount += 1
    count += 1

print ("The number of heads was", headsCount)
print ("The number of tails was", tailsCount)

input("\n\nPress the enter key to exit.")

#4

that works fine :slight_smile: You said you had no idea where to start?


#5

import random

num_heads = 0
num_tails = 0

num_tosses = 0

while num_tosses < 100:
    flip = random.randint(0, 1) # with each flip, you get 0 or 1
    if flip == 0:
        num_heads += 1  # count heads
    else:
        num_tails += 1  # count tails
    num_tosses += 1     # count tosses
        
print num_heads
print num_tails

#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.