Reputation: 13
I need to know the score of "heads" and "tails" in 5 times tossing the coin. For example, the result should be: - Heads was 3 times - Tails was 2 times
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
Upvotes: 0
Views: 2825
Reputation: 656
I have made changes to your code to count the frequency of each coin side (Heads or Tails),
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")
Upvotes: 2
Reputation: 147
Create two variables, initialize them to 0
, check the result of the coin toss in a if
block and add accordingly.
heads, tails = 0, 0
if y == "HEADS":
heads += 1
else:
tails += 1
return (heads, tails)
Upvotes: 0
Reputation: 4417
One simple solution would be to let toss
be a list of coin toss results. Starting with an empty list, you could loop until the list contained 5 results and on each toss push a new member into the list. That way you end up with a single data structure that contains all the information you need about the tosses.
Upvotes: 0
Reputation: 96018
You should have two variables, head
and 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
Or, a better solution would be having a dictionary with keys representing heads and tails, with the value representing the count.
Upvotes: 0