如何在python中添加for循环

时间:2014-02-05 04:58:12

标签: python

你好我正在研究我的计算机科学课中的一个问题,我遇到了一个错误,一切似乎都有效,但我似乎无法弄清楚我将如何加入所有的1或0

这是代码

    while True:
try:
    num = input("How many times do you want to toss the coin?")
    true = int(num)
    final = True
    if final is True:
        break
except ValueError:
        tebow =("Sorry but this is not a int please try oncce more")
        print (tebow)
for i in range(true):
ok = random.randint(0,1)
print (ok) 
# I am stuck how now I need to add up all the 1's in this case or 2's 

这段代码会做的是要求用户输入他们想扔硬币的次数然后它使用random.randomint(0,1)随机选择数字我想要做的就是输出后我需要将0添加到一个名为tails的变量中,并将1添加到一个名为heads的变量中,这就是我似乎陷入困境的地方。谢谢

2 个答案:

答案 0 :(得分:0)

即使没有发布正确的格式,答案也是基本的。您可以创建两个变量来跟踪随机选择的数字

heads = 0
tails = 0

if ok == 0:
    heads += 1
else:
    tails += 1

运营商+=与说tails = tails + 1

相同

答案 1 :(得分:0)

嗯,你真的只需要知道在N次尝试中产生了多少1。因为N - (1的数量)= 0的数量。因此,如果您将所有返回的值相加,那就是1的数量。得到它?

ones = 0  # first initialize the variable
# put for loop statement here
    ones += random.randint(0,1) # then increment the variable

我们不会为你做这件事,因为这是你的任务。但我们可以提供帮助。