Counting Heads and Tails in a coin flip program - python

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.)

Related

Python coin flip with functions

I need to create a python program that will use various functions to simulate flipping a coin 100 times and finding the largest streak of "H"'s out of 10,000 tries. I am stuck on how to finish the def main() function, specifically the counter. I also don't know if my program is calculating the streaks correctly.
def flipCoin() - returns 'H' or 'T' with the same probability as a coin.
def simulate(numFlips) - simulates flipping a coin numFlips(100) times. This function returns a list of length numFlips containing H's and T's.
def countStreak(flips_list) - iterates through the flips list passed to it and counts streaks of 'H's and returns the largest streak it finds. Keep track of the current number of heads and the current largest streak of heads in two separate variables.
As you iterate through the list, keep track of the current number of heads you've seen in a row. If you see a tail, check if the current streak of heads is larger than your current longest streak. If so, save the current streak. Then reset your heads counter.
In the main function, write a testing loop that simulates the process 10000 times.
Keep track of the current largest streak of heads and display this result after the test loop completes.
# import statements
import random
# function defintions
def flip():
coin = random.randint(0, 1)
if coin == 0:
return "H"
else:
return "T"
def simulate(num_flips):
# simulates numFlips coin flips
# returns a list of the flips
numFlips = []
for i in range(100):
numFlips.append(flip())
return numFlips
def countStreak(flips_list):
# iterates through the 'flips' list
# returns number of 'H's
count = 0
maxCount = 0
flips_list = simulate()
for i in flips_list:
if i == "H":
count += 1
if count > maxCount:
maxCount = count
else:
count = 0
return maxCount
def main():
for j in range(10000):
trial = simulate(100)
coinFlip = countStreak(1)
# need something here to track count of streaks for "H"
print("The longest streak of heads was " + str(coinFlip) +".")
if __name__ == "__main__":
main()
So there was a flaw in your code, you were running simulate() function 10000 times. But actually, you had to run it once, but return a list of 10000 items. Also, you need not check the streak every time so the check_streak() need to be out of the loop and we need to pass the result obtained from simulate(10000) into it.
Correct Code:
# import statements
import random
# function defintions
def flip():
coin = random.randint(0, 1) # better option would be to use random.choice()
if coin == 0:
return "H"
else:
return "T"
def simulate(num):
# simulates numFlips coin flips
# returns a list of the flips
numFlips = []
for i in range(num): # this needs to run num times
numFlips.append(flip())
return numFlips
def countStreak(flips_list):
# iterates through the 'flips' list
# returns number of 'H's
count = 0
maxCount = 0
for i in flips_list:
if i == "H":
count += 1
if count > maxCount:
maxCount = count
else:
count = 0
return maxCount
def main():
trial = []
for j in range(10000):
temp2 = simulate(100) # SImulate 10000 coin flips
coinFlip = countStreak(temp2) # Check streak of variable trial
trial.append(coinFlip)
# need something here to track count of streaks for "H"
# print(trial)
print("The longest streak of heads was " + str(max(trial)) +".")
if __name__ == "__main__":
main()
This Part is Optional, For optimisation
Though the logic isn't wrong, you need not make the list 1st and then check streak, you can simply check it together, it will take less time and space.
Also, your logic is correct, but this one would be better:
import random
# function defintions
def flip():
return random.choice(['H', 'T']) # using random.choice()
def simulate(num_flips):
streak = 0
temp = 0
for i in range(num_flips):
if flip() == 'H':
temp+=1 # adding one to temporary streak if it is a heads
else: # this block executes if streak is broken
if temp > streak:
streak = temp
temp = 0
return streak
def main():
trial = []
for i in range(10000):
trial.append(simulate(100))
print("The longest streak of heads was " + str(max(trial)) +".")
if __name__ == "__main__":
main()

Generating 5 unique numbers for a Powerball simulator

I wrote this from pseudo-code provided during class, and I've got most of it figured out. Only issue I'm running into is it's returning duplicate numbers for the first 5 'balls' and I can't at all figure out why. One of the lines in the pseudo-code I wasn't sure about was: "if that number is not in the main number sequence". I coded it like this:
if number != mainNumbers:
which could be the issue, but I'm not sure how else to code that.
from random import *
def drawing():
balls=0
mainNumbers=[]
while balls < 5:
number=randint(1,69)
if number != mainNumbers:
mainNumbers.append(number)
balls = balls + 1
mainNumbers.sort()
pBall=randint(1,26)
return mainNumbers, pBall
def main():
print("This program simulates a user defined number of Powerball drawings\n")
runs = int(input("What's the total number of drawings? "))
print()
count = 1
while count <= runs:
balls, pBall = drawing()
print("Drawing: {0} - The numbers are: {1} and the Powerball is: {2}".format(count, balls, pBall))
count = count + 1
main()

Why is this program not running (Python)

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.

Heads or Tails / Coin-flip program

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.

python - infinite coin flip that stops when number of heads = number of tails

I'm new to python and I'm trying to create a coinflip loop which will keep flipping and counting the number of flips until the number of heads = the number of tails, where it will stop and print the total number of flips it took to reach that. I'm trying to get the results in order to work on my maths coursework, but I cannot seem to figure out how to get it to stop or print the results, and when I do it prints 0. Here is the code I have so far:
import random
heads = 1
tails = sum(random.choice(['head', 'tail']) == 'tail'
count = 0
while True:
coinresult = random.randint(1, 2) if heads == tails:
break
print("The number of flips was {count}".format(count = heads + tails))
not sure what is going on with your indentation but try this:
import random
heads = 0 #initialize the count variables
tails = 0
while True:
coinresult = random.randint(1, 2) #flip coin
if coinresult == 1: #if result = 1 then increment heads counter
heads += 1
elif coinresult == 2: #if result = 2 then increment tails counter
tails += 1
if heads == tails: #check if counts are equal and break loop if they are
break
print("The number of flips was {count}".format(count = heads + tails))
import itertools as it
import random
def flips():
while True:
yield (random.getrandbits(1)<<1) - 1
def cumsum(seq):
s = 0
for i in seq:
s += i
yield s
def length(seq):
n = 0
for _ in seq:
n += 1
return n
print("The number of flips was {}".format(length(it.takewhile((0L).__cmp__, cumsum(flips())))))
I think this will be a nice implementation
import random
s = 0
iteration = 0
while True:
coin = random.sample([-1,1], 1)[0]
s = s + coin
iteration = iteration + 1
if s == 0:
break
print(iteration)

Categories