我正在尝试创建一个简单的头或尾程序。由于某种原因,它不起作用,我不知道为什么。有什么想法吗?
import random
counter = 0
flip = random.randint(1,2) # Initializing Values of variables
heads_counter = 0
tails_counter = 0
if flip == 1:
heads_counter +=1
counter +=1
elif flip == 2:
tails_counter +=1
counter +=1
else:
print("Invalid flip")
print("Flip is",flip)
print("Flipped The coin",counter,"Times")
print("Landed Heads",heads_counter,"Times")
print("Landed Tails",tails_counter,"Times")
答案 0 :(得分:2)
为了使数字增加,您必须在一次执行期间进行多次翻转。这是一个更简单的实现,您正在执行的程序运行num
次。
要翻转硬币100次,只需设置num = 100
from random import randint
# number of coin flips to simulate
num = 100
# simulate the coin flips
flips = [randint(1,2) for x in range(num)]
# count up the results
heads = flips.count(1)
tails = flips.count(2)
# print the results to the console
print("{0} Coin Flips".format(num))
print("{0} Heads".format(heads))
print("{0} Tails".format(tails))
这为您提供如下输出:
>>> 100 Coin Flips
>>> 49 Heads
>>> 51 Tails