我的程序正在运行用户输入次数,但它打印了很多次而不是只打印出一次,并且磁头将始终保持为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
答案 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
...