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")
Related
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")
I need help condensing my Yahtzee code. I'm familiar with loops, but I can't seem to figure out how to do it without wiping my roll each turn. It's set up to roll 5 random dice and then you choose which you want to keep. It will then roll what's left for three total rolls. I thought of making a placeholder list, but I can't make it work that way either.
Dice = [‘⚀ ’,‘⚁ ‘,’ ⚂ ‘,’ ⚃ ‘,’ ⚄ ‘,’ ⚅ ‘]
turns = 3
#first roll
first_roll = []
for _ in range(5):
roll = random.choice(dice)
first_roll.append(roll)
print(first_roll)
turns -= 1
print(f'You have {turns} turns left.')
keep = input("Which dice would you like to keep? 1 - 5: ").split()
clear()
#second roll
second_roll = []
for i in keep:
x = int(i)
j = first_roll[x-1]
second_roll.append(j)
remainder = 5 - len(second_roll)
for _ in range(remainder):
roll = random.choice(dice)
second_roll.append(roll)
print(second_roll)
turns -= 1
print(f'This is your last turn.')
keep = input("Which dice would you like to keep? 1 - 5: ").split()
clear()
#third roll
third_roll = []
for i in keep:
x = int(i)
j = second_roll[x-1]
third_roll.append(j)
remainder = 5 - len(third_roll)
for _ in range(remainder):
roll = random.choice(dice)
third_roll.append(roll)
print(third_roll)
So I'm not sure if this is exactly what you're looking for, but I created a function that lets you continuously roll for X turns and the dice pool gets progressively smaller like your code shows. I thoroughly commented the code to hopefully give you a good explanation to what I'm doing.
import random
#Dice characters
dice = ['1','2','3','4','5','6']
#Number of turns player has
turns = 3
#This is the group of dice kept by the player
kept_dice = []
def roll():
#This is the group of dice randomly chosen
rolled_dice = []
#Generate up to 5 random dice based on how many have been kept so far
for _ in range(5 - len(kept_dice)):
#Append random dice value to rolled_dice array
rolled_dice.append(random.choice(dice))
#Print roll group
print(rolled_dice)
dice_to_keep = int(input("Which dice would you like to keep? 1 - 5: "))
kept_dice.append(rolled_dice[dice_to_keep-1])
while turns != 0:
#Let the user know how many turns they have left
print(f'You have {turns} turns left.')
#Roll dice
roll()
#Subtract 1 turn
turns -= 1
#After all turns, show the kept dice:
print("Kept dice:")
print(kept_dice)
The issue is that the number of stones the computer takes differs from the number that is displayed on the screen.
I know it's cause the function is being repeated twice. But I can't find a way to store the random number generated and use that number for printing AND subtracting
[Also I know this can be done without using functions but it is required]
Here is the code:
import random
stones = random.randint(15, 30)
turn = 0
while stones > 0:
if turn == 0:
def player_announce():
print('There are', stones, 'stones. How many would you like?', end=' ')
def invalid_entry():
print('Enter a number from 1-3.')
player_announce()
player_stones = int(input(''))
if player_stones > 3 or player_stones < 1:
invalid_entry()
else:
stones = stones - player_stones
turn = 1
else:
def draw_stones():
computer_stones = random.randint(1, 3)
return computer_stones
print('There are', stones, 'stones. The computer takes', draw_stones())
stones -= draw_stones()
turn = 0
if turn == 0:
print('The computer beats the player!')
else:
print('The player beats the computer!')
The simple answer is to call draw_stones once and store the result:
computers_stones = draw_stones()
print('There are', stones, 'stones. The computer takes', computers_stones)
stones -= computers_stones
Once you've got it working, I advise you get someone to read over the whole thing for you there are a lot of things you could do better!
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
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.