Search code examples
pythonflipcoin-flipping

python - infinite coin flip that stops when number of heads = number of tails


I'm new to python and I'm trying to create a coinflip loop which will keep flipping and counting the number of flips until the number of heads = the number of tails, where it will stop and print the total number of flips it took to reach that. I'm trying to get the results in order to work on my maths coursework, but I cannot seem to figure out how to get it to stop or print the results, and when I do it prints 0. Here is the code I have so far:

import random
heads = 1
tails = sum(random.choice(['head', 'tail']) == 'tail'
count = 0
while True:
    coinresult = random.randint(1, 2) if heads == tails:
    break

print("The number of flips was {count}".format(count = heads + tails))

Solution

  • not sure what is going on with your indentation but try this:

    import random
    heads = 0 #initialize the count variables
    tails = 0
    
    while True:
        coinresult = random.randint(1, 2) #flip coin
        if coinresult == 1: #if result = 1 then increment heads counter
            heads += 1
        elif coinresult == 2: #if result = 2 then increment tails counter
            tails += 1
        if heads == tails: #check if counts are equal and break loop if they are
            break
    
    print("The number of flips was {count}".format(count = heads + tails))