0

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
2
  • 3
    You've already got a variable toss which count tosses, why not make 2 more, one counts heads and one counts tails Commented Feb 4, 2018 at 14:51
  • I'm voting to close this question as off-topic because it could be solved within the first few chapters of any decent python tutorial (variables and if statements). Commented Feb 4, 2018 at 14:58

4 Answers 4

2

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")
Sign up to request clarification or add additional context in comments.

1 Comment

Or, better: y = random.choice(counts.keys())
0

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.

Comments

0

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.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.