I want to write a coin flip or "Heads or Tails" program, but when I run it, it only gets either heads or tails everytime. I can't see why, it's a logical error so I find it hard to spot.
import random
flips = 1
coin = random.randint(1,2)
heads = 0
tails= 0
while flips <= 100:
if coin == 1:
print("Heads")
heads += 1
flips +=1
elif coin == 2:
print("tails")
tails += 1
flips +=1
print("You got", heads, "heads and", tails,"tails!")
input("Exit")
Python removes a lot of code writing that you have to do in other languages. This program is only three lines. Using the random() method, you're able to do this in a very simple matter.
Here is my code.
import random
coin_flip = ['heads','tails']
print random.choice(coin_flip)
import random
flips = 0
heads = 0
tails = 0
while flips < 100:
if random.randint(1,2) == 1:
print("heads")
heads += 1
else:
print("tails")
tails += 1
flips += 1
print("you got ", heads," heads, and ", tails," tails!")
input ("exit")
Changes made: starts from 0 and is only raising count when a flip has been made (also, flip is made every iteration as the cases are contained enough)
also, im not casting the toss to a seperate variable but comparing it immediately.
my output was:
you got 54 heads, and 46 tails!
exit
without listing the seperate flips
Note; this was the first time I ever wrote python. If there's room for optimalisation, let me know!
Try this:
import random
flips = 1
heads = 0
tails= 0
while flips <= 100:
coin = random.randint(1,2)
flips +=1
if coin == 1:
print("Heads")
heads += 1
elif coin == 2:
print("tails")
tails += 1
print("You got " + str(heads) + " heads and " + str(tails) + " tails!")
raw_input("Exit")
Edits i made:
put coins variable in loop so that a new random value is assigned on every call.
Related
For my assignment, I have to use Functions within Python to simulate a coin flip. I managed to get the coin flip to showcase heads and tales for the amount the user has inputted. However, for the next portion, I have to get the program to read how many times Heads and Tails appeared. The error I am getting is
'NameError: name 'heads' is not defined'.
import random
def main():
tosses = int(input("Please enter the amount of coin tosses:"))
coin(tosses)
count = 0
heads = 0
tails = 0
def coin(tosses):
for toss in range(tosses):
if random.randint(1, 2) == 1:
print('Heads')
heads += 1
count += 1
else:
print('Tails')
heads += 1
count += 1
print (heads)
print (tails)
main()
Problem
heads was defined out of the scope of the function coin.
Solution
Try defining the variables inside the function, then returning them. Note: the same had to be done with main.
import random
def main():
tosses = int(input("Please enter the amount of coin tosses:"))
coin(tosses)
heads, tails, count = coin(tosses)
return heads, tails
def coin(tosses):
count = 0
heads = 0
tails = 0
for toss in range(tosses):
if random.randint(1, 2) == 1:
print('Heads')
heads += 1
count += 1
else:
print('Tails')
tails += 1 # note you had this say heads before
count += 1
return heads, tails, count
heads, tails = main()
print(heads)
print(tails)
More on why this problem occurred
When you use def and create a new function, all of the variables in that function are accessible just to that function.
What was happening to you, is that you were trying to update the heads variable with heads += 1, but the function literally didn't know what the variable you were referring to is! (That variable was defined in main, and is only accessible from within the main function.)
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
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")
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.
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.
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)
I'm trying to write a program in Python that flips a coin and returns the longest series of heads and tails. It asks the user how many times to flip the coin. For some reason my program isn't running and I cant figure out why. I don't know why it isn't asking the user for the "number of flips" and "as a character string" for example.
import random
def flip():
flipValue = random.randint(1,2)
if flipValue == 1:
side = "Heads"
else:
side = "Tails"
return side
def nStreak():
number = int(input("Number of flips: "))
chars = int(input("As a character string: "))
series = 0
heads = 0
tails = 0
longest_h = 0
longest_t = 0
while series != number:
side = flip()
series += 1
if side == "Heads":
heads += 1
tails = 0
if heads == chars:
longest_h += 1
heads = 0
if side == "Tails":
tails += 1
heads = 0
if tails == chars:
longest_t += 1
tails = 0
print("Number of heads streaks: ", longest_h)
print("Number of tails streaks: ", longest_t)
When I run it I get nothing.
You need to call the function at the last line.
nStreak()
Or else it won't execute the code.
At the bottom of your script add nStreak() with no identation.
So brand new to python, and I've come across something I can't explain, much less put in to words to find a possible answer for. I've made a little coin flipping program:
import random
print("I will flip a coin 1000 times")
input()
flips = 0
heads = 0
while flips < 1000:
if random.randint(0, 1) == 1:
heads = heads + 1
flips = flips + 1
print()
print("Out of 1000 coin tosses, heads came up " + str(heads) + " times!")
This version of the program does not work, it tells me after 1000 flips, there have been 1000 heads every time.
import random
print("I will flip a coin 1000 times")
input()
flips = 0
heads = 0
while flips < 1000:
if random.randint(0, 1) == 1:
heads = heads + 1
flips = flips + 1
print()
print("Out of 1000 coin tosses, heads came up " + str(heads) + " times!")
This version of the program works perfectly however, notice I have changed the indentation of "flips" in the while loop.
Can anyone tell me why this is? Thanks in advance!
Python language is indentation dependent. Unlike most C-based languages, it uses indentation to delimit blocks.
So your two scripts have a different semantic:
if random.randint(0, 1) == 1:
heads = heads + 1
flips = flips + 1
...will increment both variables if the condition is True.
if random.randint(0, 1) == 1:
heads = heads + 1
flips = flips + 1
...will increment heads only if the condition is True, and will always increment flips
That's because if that "flips" line is in the if, then it will only execute if it is heads. Therefore, your coin flip count only increments when it's a head, and so by the time flips reached 1000, it means you've executed the if 1000 times and got 1000 heads.
(When you get a tail, flips won't increment and the loop keeps going and nothing happens)
I've been writing a program in python that simulates 100 coin tosses and gives the total number of tosses. The problem is that I also want to print the total number of heads and tails.
Here's my code:
import random
tries = 0
while tries < 100:
tries += 1
coin = random.randint(1, 2)
if coin == 1:
print('Heads')
if coin == 2:
print ('Tails')
total = tries
print(total)
I've been racking my brain for a solution and so far I have nothing. Is there any way to get the number of heads and tails printed in addition to the total number of tosses?
import random
samples = [ random.randint(1, 2) for i in range(100) ]
heads = samples.count(1)
tails = samples.count(2)
for s in samples:
msg = 'Heads' if s==1 else 'Tails'
print msg
print "Heads count=%d, Tails count=%d" % (heads, tails)
import random
total_heads = 0
total_tails = 0
count = 0
while count < 100:
coin = random.randint(1, 2)
if coin == 1:
print("Heads!\n")
total_heads += 1
count += 1
elif coin == 2:
print("Tails!\n")
total_tails += 1
count += 1
print("\nOkay, you flipped heads", total_heads, "times ")
print("\nand you flipped tails", total_tails, "times ")
You have a variable for the number of tries, which allows you to print that at the end, so just use the same approach for the number of heads and tails. Create a heads and tails variable outside the loop, increment inside the relevant if coin == X block, then print the results at the end.
Keep a running track of the number of heads:
import random
tries = 0
heads = 0
while tries < 100:
tries += 1
coin = random.randint(1, 2)
if coin == 1:
heads += 1
print('Heads')
if coin == 2:
print ('Tails')
total = tries
print('Total heads '.format(heads))
print('Total tails '.format(tries - heads))
print(total)
import random
tries = 0
heads=0
tails=0
while tries < 100:
tries += 1
coin = random.randint(1, 2)
if coin == 1:
print('Heads')
heads+=1
if coin == 2:
print ('Tails')
tails+=1
total = tries
print(total)
print tails
print heads
tosses = 100
heads = sum(random.randint(0, 1) for toss in range(tosses))
tails = tosses - heads
You could use random.getrandbits() to generate all 100 random bits at once:
import random
N = 100
# get N random bits; convert them to binary string; pad with zeros if necessary
bits = "{1:>0{0}}".format(N, bin(random.getrandbits(N))[2:])
# print results
print('{total} {heads} {tails}'.format(
total=len(bits), heads=bits.count('0'), tails=bits.count('1')))
Output
100 45 55
# Please make sure to import random.
import random
# Create a list to store the results of the for loop; number of tosses are limited by range() and the returned values are limited by random.choice().
tossed = [random.choice(["heads", "tails"]) for toss in range(100)]
# Use .count() and .format() to calculate and substitutes the values in your output string.
print("There are {} heads and {} tails.".format(tossed.count("heads"), tossed.count("tails")))
I ended up with this.
import random
flips = 0
heads = 0
tails = 0
while flips < 100:
flips += 1
coin = random.randint(1, 2)
if coin == 1:
print("Heads")
heads += 1
else:
print("Tails")
tails += 1
total = flips
print(total, "total flips.")
print("With a total of,", heads, "heads and", tails, "tails.")
Here is my code. Hope it will help.
import random
coin = random.randint (1, 2)
tries = 0
heads = 0
tails = 0
while tries != 100:
if coin == 1:
print ("Heads ")
heads += 1
tries += 1
coin = random.randint(1, 2)
elif coin == 2:
print ("Tails ")
tails += 1
tries += 1
coin = random.randint(1, 2)
else:
print ("WTF")
print ("Heads = ", heads)
print ("Tails = ", tails)
import random
print("coin flip begins for 100 times")
tails = 0
heads = 0
count = 0
while count < 100: #to flip not more than 100 times
count += 1
result = random.randint(1,2) #result can only be 1 or 2.
if result == 1: # result 1 is for heads
print("heads")
elif result == 2: # result 2 is for tails
print("tails")
if result == 1:
heads +=1 #this is the heads counter.
if result == 2:
tails +=1 #this is the tails counter.
# with all 3 being the count, heads and tails counters,
# i can instruct the coin flip not to exceed 100 times, of the 100 flips
# with heads and tails counter,
# I now have data to display how of the flips are heads or tails out of 100.
print("completed 100 flips") #just to say 100 flips done.
print("total tails is", tails) #displayed from if result == 2..... tails +=1
print("total heads is", heads)