我需要知道5次投掷硬币的“头”和“尾”的得分。 例如,结果应该是: - 头部是3次 - 尾巴是2次
import random
print("Heads or tails. Let's toss a coin five times.\n")
toss = 1
while toss <= 5:
coin = ["HEADS", "TAILS"]
y = random.choice(coin)
print("Toss number:", toss, "is showing:", y)
toss = toss + 1
答案 0 :(得分:2)
我已对代码进行了更改,以计算每个硬币面(头部或尾部)的频率,
import random
print("Heads or tails. Let's toss a coin five times.\n")
toss = 1
counts = {"HEADS": 0, "TAILS": 0}
while toss <= 5:
coin = ["HEADS", "TAILS"]
y = random.choice(coin)
counts[y] += 1
print("Toss number:", toss, "is showing:", y)
toss = toss + 1
print("Heads was " + str(counts["HEADS"]) + " times - Tails was " + str(counts["TAILS"]) + " times")
答案 1 :(得分:0)
您应该有两个变量,head
和tail
:
import random
print("Heads or tails. Let's toss a coin five times.\n")
head = tail = 0
for i in range(5):
coin = ["HEADS", "TAILS"]
y = random.choice(coin)
print("Toss number:", i, "is showing:", y)
if y == "HEADS":
head += 1
elif y == "TAILS":
tail += 1
或者,更好的解决方案是使用带有表示头部和尾部的键的字典,其值代表计数。
答案 2 :(得分:0)
一个简单的解决方案是让toss
成为抛硬币结果列表。从空列表开始,您可以循环直到列表包含5个结果,并在每次折腾时将新成员推入列表。这样,您最终会得到一个包含所有关于投掷所需信息的数据结构。
答案 3 :(得分:0)
创建两个变量,将它们初始化为0
,检查if
块中掷硬币的结果并相应添加。
heads, tails = 0, 0
if y == "HEADS":
heads += 1
else:
tails += 1
return (heads, tails)