如何计算随机掷硬币产生的 "heads" 和 "Tails" 的数量?

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

我想根据用户输入的他们想要的抛硬币数量计算并输出正面和反面出现的次数。

到目前为止,我没有得到正面:1 和没有尾巴:1

我还想知道需要多少次抛硬币才能获得所有正面然后所有反面的列表,但我首先在努力解决这个问题!

这是我的代码:

# 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()

这些修改解决了您的问题并与之前的评论保持一致。

import random
heads = "Heads"
tails = "Tails"
heads_count = 0
tails_count = 0

def main():
    tosses = int(input("Enter number of tosses:"))
    coins = coin(tosses)
    print("Total number of heads:",coins[0])
    print("Total number of tails:", coins[1])

def coin(tosses):
    global heads_count
    global tails_count
    for toss in range(tosses):
        # Simulate the coin toss.
        if random.randint(1, 2) == 1:
            print(heads)
            heads_count+=1
        else:
            print(tails)
            tails_count+=1
    return (heads_count,tails_count)

main()

我对您的代码进行了一些修改!它不需要像您设计的那样复杂。如果您有任何问题,请告诉我!

# 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()

这是一个替代解决方案,它使用 collections 模块来 return 抛出的正面和反面的数量:

from random import choice
from collections import Counter

count = int(input("Enter number of tosses: "))
results = Counter([choice(['heads','tails']) for _ in range(count)])
heads, tails = results['heads'], results['tails']

print("total number of heads:", heads)
print("total number of tails:", tails)