Python flipping x coins x times using loops but receiving odd output - python

I'm new to python and coding in general. I have an assignment for class to write a program that uses a loop to flip multiple coins multiple times. The code must:
ask for the number of coins and how many times to flip those coins.
Must ask again if the input is less then 0.
Print the result of flipping each coin the specified number of times and must be random.
Then print the total number of heads and tails.
I do have to use random so suggestions of other modules or better ways to achieve randomization aren't something I'm looking for, thank you.
The output should look something like:
How many coins do you want to flip? 2
How many times do you want to flip each coin? 2
Coin 1
Flip: 1; Result: Heads
Flip: 2; Result: Tails
Coin 2
Flip: 1; Result: Tails
Flip: 2; Result: Heads
There were 2 Tails in total
There were 2 Heads in total
Here's what I tried: (I'm having to use my phone due to some irl problems to ask this so if the format is off I'm sorry!)
import random
heads = 0
tails = 0
coins = int(input("How many coins: "))
while coins !="":
if coins \<= 0:
print ("Invalid input")
coins = int(input("How many coins: "))
else:
flips = int(input("How many times to flip: "))
if flips \<= 0:
print ("Invalid input")
flips = int(input("How many times to flip: "))
else:
for n in range (0, coins):
for i in range (0, flips):
print (" ")
print ("Coin %0d" %n)
print (" ")
n = coins + 1
for flip in range (0, flips):
flip = random.randint(0,1)
if flip == 0:
heads += 1
print ("Flips: %0d;" %i, "Result: heads")
else:
tails += 1
print ("Flip: %0d;" %i, "Result: tails")
i = flips + 1
print ("total heads:", heads)
print ("total tails:", tails)
break
What I get varies wildly by the numbers I input. I might flip 4 coins 3 times and it flips 6 coins. Or 1 coin 3 times and it flips 6 coins. But 1 coin 2 times flips 1 coin 2 times. The numbers counting the coins and flips also don't work right. I get results like:
Coin 0
Flip: 0; Result: Tails
Flip: 3; Result: Heads
Coin 2
Flip: 1; Result: Tails
Flip: 3; Result: Tails.
I'm stumped and at this point all the code looks like abc soup. Any help is appreciated.

I'd suggest re-looking into your code's flow control and variable usage once you get to the evaluation stage (when you are doing the coin flipping).
Specifically, you appear to be using the number of flips for two distinct loops: for i in range (0, flips): and for flips in range (0, flips):.
Additionally, the second one (for flips in range (0, flips):) is overwriting the flips variable which you are using to store the number of flips per coin that the user requested.

I had put in the line 'for flip in range (0, flips)' not thinking that moving the 'for i in range (0, flips)' would tell the program the same thing. Which I wouldn't have figured out without Benjamin Davis or Scott Hunter and I greatly appreciate you both!
So the middle part should actually be:
else:
for n in range (1, coins +1)
print (" ")
print ("Coin %0d" %n)
print (" ")
for i in range (1, flips +1)
flip = random.randit (0,1)
if flip == 0:
heads += 1
print ("Flip: %0d;" %i, "Result: heads")
else:
tails += 1
print ("Flip: %0d;" %i, "Result: tails")

Related

Python program that simulates rolling a 6 sided die and adds up the result of each roll till you roll a 1

so this is the code I wrote that attempts to answer the question in the title :
import random
print("Well, hello there.")
while True:
a = random.randint(1,6)
sum = 0
if(a==1): #If a one is indeed rolled, it just shows rolled a 1 and 'Pigs out' and makes the score equal to 0(player score that is) and is a sort of a GameOver
print("Pigged out!")
break #To get out of the loop
else:
while(sum<=20):
sum += a
print(sum)
The program should hold the score till it reaches 20(or more) and display it. It essentially represents a single turn of 'Pig'. I am unable to figure out where I am going wrong with this? Any suggestions would be helpful.
An example of a sample output:
-rolled a 6
-rolled a 6
-rolled a 5
-rolled a 6
-Turn score is 23
If I understand rightly then you can simplify this quite a lot, like this:
import random
print("Well, hello there.")
score = 0
while score < 20:
a = random.randint(1,6)
print("A {} was rolled".format(a))
score += a
if a == 1:
print("Pigged out!")
score = 0
break
print("Turn score is {}".format(score))
If you just want to display the sum once it's greater than 20, shouldn't you unindent the print(sum) to the left? Essentially:
while(sum<=20):
sum += a
print(sum)
It would be nice if you could clarify what you want the output to be and what it is currently doing.
is this what you want?
import random
print("Well, hello there.")
sum=0
while True:
a = random.randint(1,6)
sum+=a
if(a==1): #If a one is indeed rolled, it just shows rolled a 1 and 'Pigs out' and makes the score equal to 0(player score that is) and is a sort of a GameOver
print("Pigged out!")
break #To get out of the loop
else:
if sum<=20:
sum += a
print(sum)
else:
print(sum,'limit reached')
break
You should break after the sum is more than 20
else:
while(sum<=20):
sum += a
print(sum)
break
Edit:
import random
print("Well, hello there.")
while True:
a = random.randint(1,6)
sum = 0
if(a==1): #If a one is indeed rolled, it just shows rolled a 1 and 'Pigs out' and makes the score equal to 0(player score that is) and is a sort of a GameOver
print("Pigged out!")
break #To get out of the loop
else:
if not SumWasReached:
while(sum<=20):
a = random.randint(1,6)
sum += a
print(sum)
SumWasReached ==True:
else:
while(a!=1):
a = random.randint(1,6)
break

Creating dice simulator in Python, how to find most common roll

import random
#Making sure all values are = to 0
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
#Loop for rolling the die 100 times
for r in range(0, 100):
roll = random.randint(1, 6)
if roll == 1:
one += 1
elif roll == 2:
two += 1
elif roll == 3:
three += 1
elif roll == 4:
four += 1
elif roll == 5:
five += 1
elif roll == 6:
six += 1
#print how many times each number was rolled
print(one)
print(two)
print(three)
print(four)
print(five)
print(six)
#How many times the 3 was rolled
print("The 3 was rolled", three, "times!")
#Average roll between all of them
print("The average roll was", (one * 1 + two * 2 + three * 3 + 4 * four + 5 * five + 6 * six)/100)
I am trying to make it so it prints out
"number is the most common roll." for whichever the roll is.
Just trying to do this is the most simple way, and I'm confused on how to do it. I tried to do like if one > two > three etc etc. but that did not work.
Choosing an appropriate data structure to gain maximum leverage of a language’s core features is one of the most valuable skills a programmer can develop.
For this particular use case, it’s best to use an iterable data type that facilitates operations (e.g. sort, obtain the maximum) on the collection of numbers. As we want to associate a number (1-6) with the number of times that number was rolled, a dictionary seems like the simplest data structure to choose.
I’ve re-written the program to show how its existing functionality could be re-implemented using a dictionary as its data structure. With the comments, the code should be fairly self-explanatory.
The tricky part is what this question is actually asking: determining the number rolled most often. Instead of manually implementing a sorting algorithm, we can use the Python built-in max function. It can accept an optional key argument which specifies the function that should be applied to each item in the iterable object before carrying out the comparison. In this case, I chose the dict.get() method which returns the value corresponding to a key. This is how the dictionary of roll results is compared by the number of rolls for each result for determining the number rolled most often. Note that max() only returns one item so in the case of a tie, only one of the results will be printed (see Which maximum does Python pick in the case of a tie?).
See also: How do I sort a dictionary by value?
import random
NUM_ROLLS = 100
DIE_SIDES = 6
# Create the dictionary to store the results of each roll of the die.
rolls = {}
#Loop for rolling the die NUM_ROLLS times
for r in range(NUM_ROLLS):
roll_result = random.randint(1, DIE_SIDES)
if roll_result in rolls:
# Add to the count for this number.
rolls[roll_result] += 1
else:
# Record the first roll result for this number.
rolls[roll_result] = 1
# Print how many times each number was rolled
for roll_result in range(1, 7):
print("The number", str(roll_result), "was rolled", str(rolls[roll_result]), "times.")
#How many times the 3 was rolled
print("The number three was rolled", str(rolls[3]), "times.")
#Average roll between all of them
sum = 0
for roll_result in rolls:
sum += roll_result * rolls[roll_result]
print("The average roll result was", str(sum/NUM_ROLLS))
# The number rolled most often.
print(str(max(rolls, key=rolls.get)), "is the most common roll result.")

modified coin toss program won't run

So I have to complete an assignment in which a coin toss is simulated and the number of flips, tails, and heads must be counted.
My first problem was that I could not get the number of heads or tails to display, fixed that, but then it was doubling(ex: I request 50 flips and the total amount of heads and tails would equate to 100), figured out that I had accidentally made it so it was counting up twice instead of once per flip, when I changed that the program just doesn't seem to run.
When I input the amount of times I would like the coin to flip and hit enter it just does nothing and goes to the next line on my terminal. I have removed all white space off my program in case of infinite looping other than that I cannot figure out what is causing this.
Thank you for any help.
You need to remove below line, otherwise it will keep on looping
count +=1
Because, at the same time you are incrementing head or tail as well.
Assuming, you provided input 1 then, it will check
head+tail < count # 0 < 1 , which is true
then assuming coin=1 then,
count+=1
head= head+1
For the next loop
head+tail < count # 1 < 2 , which is true
The issue is that you increment your count variable, alongside your head and tails counts. So you are in a while loop aiming for a moving target. I am not attempting to compete with Ravi for the accepted answer, but here is a simplified version of your code.
You needn't use a while loop, as you know how many iterations you will do. In this case a for loop is the appropriate tool.
from random import choice
heads = tails = 0
count = int(input('how many flips? '))
for _ in range(count):
if choice([True, False]):
heads += 1
else:
tails += 1
print('you flipped %d times' % count)
print('you flipped %d heads and %d tails' % (heads, tails))

Can't figure out how to make a python coin toss program loop back to a certain point once the whole process of the toss has been completed

I have been banging my head against the wall for a few hours now trying to figure this out so any help is greatly appreciated. What I'm trying to do is loop the program upon a Y input for a Y/N question, specifically when Y is inputed I want it to react the way it does as shown in the sample output.
Here is my code:
import random
def main():
name = eval(input("Hello user, please enter your name: "))
print("Hello", name ,"This program runs a coin toss simulation")
yn = input("Would you like to run the coin toss simulation?(Y/N):")
if yn == Y:
elif yn == N:
print("Ok have a nice day!")
heads = 0
tails = 0
count = tails + heads
count = int(input("Enter the amount of times you would like the coin to flip: "))
if count <= 0:
print("Silly rabbit, that won't work")
while tails + heads < count:
coin = random.randint(1, 2)
if coin ==1:
heads = heads + 1
elif coin == 2:
tails = tails + 1
print("you flipped", count , "time(s)")
print("you flipped heads", heads , "time(s)")
print("you flipped tails", tails , "time(s)")
main()
Here is the sample output that I'm looking for:
Hello user, please enter your name: Joe
Hello Joe this program runs a coin toss simulation
Would you like to run the coin toss simulation?(Y/N):Y
Enter the amount of times you would like the coin to flip:50
you flipped 50 times
you flipped heads 26 times
you flipped tails 24 times
Would you like to run another coin toss simulation?(Y/N):Y
Enter the amount of times you would like the coin to flip:100
you flipped 100 times
you flipped heads 55 times
you flipped tails 45 times
Would you like to run another coin toss simulation?(Y/N):N
Ok have a nice day!
I think you should say on line 6 if yn == 'Y' and not if yn == Y. You treat Y as a variable while it is actually a string from the input.
To run your coin toss simulation multiple times you can put it inside a while loop.
Your if yn == Y: test won't work because you haven't defined the variable Y, so when Python tries to execute that line you get a NameError. What you actually should be doing there is to test the value of yn against the string 'Y'.
I've made a couple of other minor adjustments to your code. I got rid of that potentially dangerous eval function call, you don't need it. I've also made a loop that asks for the desired flip count; we break out ofthe loop when count is a positive number.
import random
def main():
name = input("Hello user, please enter your name: ")
print("Hello", name , "This program runs a coin toss simulation")
yn = input("Would you like to run the coin toss simulation?(Y/N): ")
if yn != 'Y':
print("Ok have a nice day!")
return
while True:
heads = tails = 0
while True:
count = int(input("Enter the amount of times you would like the coin to flip: "))
if count <= 0:
print("Silly rabbit, that won't work")
else:
break
while tails + heads < count:
coin = random.randint(1, 2)
if coin ==1:
heads = heads + 1
else:
tails = tails + 1
print("you flipped", count , "time(s)")
print("you flipped heads", heads , "time(s)")
print("you flipped tails", tails , "time(s)")
yn = input("Would you like to run another coin toss simulation?(Y/N): ")
if yn != 'Y':
print("Ok have a nice day!")
return
main()
This code is for Python 3. On Python 2 you should use raw_input in place of input, and you should also put
from future import print_function
at the top of the script so you get the Python 3 print function instead of the old Python 2 print _statement.
There are several improvements that can be made to this code. In particular, it should handle a non-integer being supplied for the count. This version will just crash if it gets bad input. To learn how to fix that, please see Asking the user for input until they give a valid response.

python, repeat random.randint?

I am new to python and i would like to know how to make the code to repeat the random.randint part 100 times.
#head's or tail's
print("you filp a coin it lands on...")
import random
heads = 0
tails = 0
head_tail =random.randint(1, 2,)
if head_tail == 1:
print("\nThe coin landed on heads")
else:
print("\nThe coin landed on tails")
if head_tail == 1:
heads += 1
else:
tails += 1
flip = 0
while True :
flip +=1
if flip > 100:
break
print("""\nThe coin has been fliped 100 times
it landed on heads""", heads, """times and tails""", tails,
"""times""")
input("Press the enter key to exit")
You could do it all in one line with a list comprehension:
flips = [random.randint(1, 2) for i in range(100)]
And count the number of heads/tails like this:
heads = flips.count(1)
tails = flips.count(2)
Or better yet:
num_flips = 100
flips = [random.randint(0, 1) for _ in xrange(num_flips)]
heads = sum(flips)
tails = num_flips - heads
First of all, I would replace that while loop with:
for flip in xrange(100):
...
Secondly, to conduct 100 random trials, move the randint() call -- as well as everything else that you want to perform 100 times -- inside the body of the loop:
for flip in xrange(100):
head_tail = random.randint(1, 2)
...
Finally, here is how I would do the whole thing:
heads = sum(random.randint(0, 1) for flip in xrange(100))
tails = 100 - heads
You would use range(100), since you're on Python3.x which creates a list from 0 to 99 (100 items). It'll look something like this:
print("you flip a coin it lands on...")
import random
heads = 0
tails = 0
for i in xrange(100):
head_tail = random.randint((1, 2))
if head_tail == 1:
print("\nThe coin landed on heads")
else:
print("\nThe coin landed on tails")
if head_tail == 1:
heads += 1
else:
tails += 1
print("""\nThe coin has been fliped 100 times
it landed on heads""", heads, """times and tails""", tails,
"""times""")
input("Press the enter key to exit")
for flip in range(100):
head_tail = random.randint(1, 2)
if head_tail == 1:
print("\nThe coin landed on heads")
else:
print("\nThe coin landed on tails")
if head_tail == 1:
heads += 1
else:
tails += 1
I'm new in Python and generally in programming, but I created my own code base on 1 day programming practice. Coin flip coding exercise is one of the first from the book I study now. I tried to find solution on the internet and I found this topic.
I was aware to use any code from this topic because few functions used in previous answers were not familiar to me.
To anyone in similar situation: Please feel free to use my code.
import random
attempts_no = 0
heads = 0
tails = 0
input("Tap any key to flip the coin 100 times")
while attempts_no != 100:
number = random.randint(1, 2)
attempts_no +=1
print(number)
if number == 1:
heads +=1
elif number ==2:
tails +=1
print("The coin landed on heads", heads, "times")
print("The coin landed on heads", tails, "times")

Categories

Resources