Reputation: 51
I'm very new to Python and I need to create a program that automatically runs heads or tails (no user input needed) and stops after one of three conditions is met. 1) 8 heads flipped. 2) 9 tails flipped. 3) 3 consecutive heads flipped.
I want ideas on how to approach this problem, not asking to do the hw. I've reviewed many similar questions, but none have helped so far.
text = ("""Welcome to the coin flip simulator!
Simulating coin flips...""")
print(text)
import random
heads = 0
tails = 0
for i in range(1,1000,1):
coin = random.randint(0,1)
if coin == 0:
print("heads")
else:
print("tails")
It prints heads / tails indefinitely, but it should stop after the condition is met.
Upvotes: 0
Views: 65
Reputation: 956
Take a step back and look at the problem. You really have three things left to do:
You are initializing variables for the number of heads and tails, but you aren't keeping track of them when they come. That should be easy to fix. When you see a head, add one to heads. Do the same for tails
Since every loop is a coin flip, you need to check if the conditions are met at either the start of the end of the loop. How do you run code if a condition is met? With some control flow (specifically if statements). You are now keeping track of the conditions (at least two of them, you need another counter for the number of consecutive heads). And you are going to execute code when the condition is met.
Last thing to do is exit the loop after the condition is met. I'll give you this one for free. To exit a while loop you can just call break
. This will exit the nearest loop and continue executing code after the loop.
Now you are able to track the conditions, check it after a coin toss, and exit when the condition is met. For your homework, you can put the pieces together.
Upvotes: 1
Reputation: 2919
In the spirit of not doing your homework for you, you should look at using flow control objects and conditionals
4.4. break and continue Statements, and else Clauses on Loops
The break statement, like in C, breaks out of the innermost enclosing for or while loop.
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:
Your loop (if it is truly indefinite) should be something like while True:
as opposed to just going through 10000 iterations as well.
Upvotes: 0