Search code examples
pythonrandomcounter

how to count amount of "heads" and amount of "Tails" produced from random coin flip?


i want to count and output the amount of times heads and tails are occur in a coin toss based of a users input of amount of coin tosses they want.

so far with this I get no of heads: 1 and no of tails: 1

i also want to get a count of how many coin flip tries it takes to get a list of all heads and then of all tails, but im struggling with this first!

here is my code:

# This program simulates tosses of a coin.
import random
heads = "Heads"
tails = "Tails"
count = 0

def main():
    tosses = int(input("Enter number of tosses:")) 
    coin(tosses)
    print("Total number of heads:",(heads.count(heads)))
    print("Total number of tails:", (tails.count(tails)))
    
#end of main function    

def coin(tosses):
    for toss in range(tosses):
        # Simulate the coin toss.
        if random.randint(1, 2) == 1:
            print(heads)
        else:
            print(tails)
    return (heads.count(heads),(tails.count(tails)))
        # end of if statement
     #end of for loop   
#end of coin function

            
# Call the main function.
main()

Solution

  • I've made some edits to your code! It doesn't need to be as complicated as you made it to be. Let me know if you have any questions!

    # This program simulates tosses of a coin.
    import random
    
    # function to toss coins and increment head/tail counts
    def coin(tosses):
    
        # store the counts of each respective result
        heads = 0
        tails = 0
    
        for toss in range(tosses):
            # simulate the coin toss
            if random.randint(1, 2) == 1:
                print("Heads!")
                heads+=1 # increment count for heads
            else:
                print("Tails!")
                tails+=1 # increment count for tails
    
        return heads, tails
    
    # main function
    def main():
        # get user input
        tosses = int(input("Enter number of tosses:")) 
    
        # toss coins
        heads, tails = coin(tosses)
    
        # print final result
        print("Total number of heads:", heads)
        print("Total number of tails:", tails)
    
    
    # call the main function
    main()