kora
kora

Reputation: 19

Coin flip loop with specific number of heads

My instructions: Write a program that “flips” a coin repeatedly and displays the results to the screen.
The program only stops when a specific # of heads has been flipped. That number of heads is specified by the user. Your program should output the total number of flips made during execution.

My question is that I don’t know how long to generate Heads or Tails separately in a random manner. Im not sure how to incorporate a while or for loop in this or a counter either. Im very confused on what to do.

My code: (it’s botched because I really don’t know how what I should write)

import random

tails1= 0
heads= 1

heads_flips= int(input("Enter the amount of flips for heads:"))

while tails1 < heads_flips:
    if heads_flips > 0 print Heads amount of head_flips
    print("Heads", heads_flips)

Upvotes: 0

Views: 379

Answers (1)

lmiguelvargasf
lmiguelvargasf

Reputation: 69705

There are multiple ways to solve this problem, but considering you are a beginner.

import random

tail = 0
head = 1

number_of_heads = 0
heads_flips= int(input("Enter the amount of flips for heads:"))


while number_of_heads < heads_flips:
    flip = random.randrange(2)
    if flip == head:
        number_of_heads += 1
    print("Heads", number_of_heads)

In essence, you are going to generate a random number, either 0 or 1 with random.randrange(2). We have set that 0 will represent that it was tails and 1 that it was heads.

The variable number_of_heads is increased every time 1 was generated, and eventually, it will make the condition of our while loop becomes False.

Upvotes: 0

Related Questions