随机硬币翻转游戏。打印三行头尾

时间:2014-03-09 17:05:50

标签: python random

我的程序正在运行用户输入次数,但它打印了很多次而不是只打印出一次,并且磁头将始终保持为0,尾部上升一,直到达到翻转次数。

#import random for random 0 or 1
import random

#assign variables
heads = 0
tails = 0
count = 0

#initiate flips
flips = input("Enter the number of flips ")

#begin loop and increment heads or tails
while flips > count:

    coin = random.randint(0, 1)

    if coin == 0:

        count = count + 1

        heads = heads + 1

    elif coin == 1:

        count = count + 1

        tails = tails + 1
    else:
        print "There is a problem"
    print "The number of heads is" , heads, "and the number of tails is" , tails

1 个答案:

答案 0 :(得分:1)

你应该 unindent print语句,以便它位于while循环之外:

而不是:

    else:
        print "There is a problem"
    print "The number of heads is" , heads, "and the number of tails is" , tails

试试这个:

    else:
        print "There is a problem"
print "The number of heads is" , heads, "and the number of tails is" , tails

如果您想要无限期地询问用户翻转,请在while循环中包围整个代码:

import random

while True:
    #assign variables
    heads = 0
    ...