This is the code -
import random
def game():
randno = random.randint(1,11)
a = int(input("guess a number from 1 to 10 - "))
if randno == a:
for d in range(0, 1000001):
d+=10
print ("gud, score increased by 10")
return d
else :
return (0)
with open("hiscore.txt", "r") as a:
S = a.read(int())
HS = game()
if S=="":
with open("hiscore.txt", "w") as b:
b.write(str(HS))
elif HS>S:
with open("hiscore.txt", "w") as b:
b.write(str(HS))
The score should be increased by 10 every time u guess the correct number, the score will increase by 10 and should appear in another file called hiscore.txt. the issue is that the score does get increased but only once. this means that it only increases the score to 10 the first time and does not increase after that no matter how many time you guess correct
I suppose that you want:
def game():
d = 0
for _ in range(0, 1000001):
randno = random.randint(1,11)
a = int(input("guess a number from 1 to 10 - "))
if randno == a:
d += 10
print ("gud, score increased by 10")
return d
Move the no loop outside, and skip the else part. Also return outside the loop.
I've been trying to write it so it pulls from
roll_dice = random.randint(1,6)
but its only been set to one number so it's always equal to the same number. here's the full code:
import random
roll_dice = random.randint(1,6)
rolls = 0
check = 0
while check <= 20:
roll_dice
if roll_dice < 4:
check = check + 1
rolls = rolls + 1
elif roll_dice > 0:
rolls += rolls + 1
elif check == 20:
print("it took", rolls, "to reach 20 rolls under 3")
Put the roll_dice = random.randint(1, 6) inside the while loop so that each iteration the value of roll_dice changes, and is a random number from 1 to 6.
I.e, without changing the structure of your code too much,
import random
rolls = 0
check = 0
while check <= 20:
rolls = rolls + 1 #add 1 to rolls counter
roll_dice = random.randint(1,6) #Set roll_dice to random int from 1-6
if roll_dice < 4: #if it is 3 or lower, add 1 to check
check = check + 1
if check == 20: #if 20 rolls of 3 or less, then print and stop loop
print("it took", rolls, "rolls to reach 20 rolls under 3")
break
Sample Output:
it took 32 rolls to reach 20 rolls under 3
I'm stuck on a dice exercise. For each dice that rolls 6, they need to be excluded from the count and rolled again. Problem is that I don't know how to change the value of a for range loop whilst looping through it, and I'm not sure how to attack it otherwise. Here's where I'm at:
numRolls = 10
initSum = 0
for i in range(0,numRolls):
diceScore = random.randint(1,6)
if(diceScore == 6):
print("You rolled a 6! You receive two extra rolls.")
numRolls = numRolls + 2
# Not making its way to the top of the for-loop
else:
totalSum = initSum + diceScore
print("Done! You've rolled a total of ",totalSum)
totalSum = 0
I'm guessing numRolls in the for-loop is out of scope. The alternative solutions I've come up with would mean absolutely endless amount of separate rolls. Randoming between 1 and 5 is not a viable option.. :)
Can someone point me in the right direction here?
Use a while loop and initialize the counter outside the loop. Then increment both, the counter and numRolls, as and when you want inside the loop
numRolls = 10
rollsSoFar = 0
initSum = 0
while rollsSoFar <= nulRolls:
diceScore = random.randint(1,6)
if(diceScore == 6):
print("You rolled a 6! You receive two extra rolls.")
numRolls = numRolls + 2
else:
totalSum = initSum + diceScore
rollsSoFar += 1
print("Done! You've rolled a total of ",totalSum)
totalSum = 0
Edit: added explanation for why this works
When you create a for loop like for i in range(0,numRolls) you are calling the function range() and passing it parameters 0 and numRolls. range() then gives you back a generator (let's call this generator rollsGenerator) that you iterate over. This generator has been created to give you values 0 to numRolls-1 inclusive.
So your for-loop effectively evaluates to something like for i in rollsGenerator before the first iteration begins.
Then, inside the loop, when you increment the value of numRolls, it doesn't change the number of iterations because rollsGenerator has already been created with the original value of numRolls. The for-loop does not call range(0,numRolls) on every iteration, and so the generator stays the same no matter how you change numRolls.
By using a while-loop, you are basically changing your code to check the latest value of numRolls on each iteration and you skip the whole generator business.
Consider this smaller example:
for i in range(0, 3):
i = i + 1
This is equivalent to
i = 0
i = i + 1
i = 1
i = i + 1
i = 2
i = i + 1
I'm sure you see why your idea doesn't work.
Use while instead of for.
If you count down instead of up, you don't need any more variables.
while numRolls > 0:
numRolls = numRolls - 1
diceScore = random.randint(1,6)
if(diceScore == 6):
print("You rolled a 6! You receive two extra rolls.")
numRolls = numRolls + 2
else:
totalSum = initSum + diceScore
print("Done! You've rolled a total of ",totalSum)
totalSum = 0
I have to simulate a points game where the first person to reach 11 points and win by 2 clear points wins the game
I have used a function to decide who wins a point
def simulatePoint(winProbabilityA, winProbabilityB):
rNumber = random.random()
if rNumber - winProbabilityA <= 0:
# A wins the game
return 0
elif rNumber - winProbabilityA > 0:
# B wins the game
return 1
and another one to simulate a game
def simulateGame (playerA_winProb, playerB_winProb):
gameWon = False
pointsA = 0
pointsB = 0
while gameWon == False:
# Simulate point
point = simulatePoint(playerA_winProb, playerB_winProb)
if point == 0:
pointsA += 1
elif point == 1:
pointsB += 1
# Checks for points to be equal to 11
if (pointsA == 11) and (pointsA - pointsB >= 2):
# A wins the game
gameWon = True
return 0
elif (pointsB == 11) and (pointsB - pointsA >= 2):
# B wins the game
gameWon = True
return 1
This is where i believe i am going wrong, i think the while loop is causing the code to run slow
Any help is greatfully accepted
What if the difference becomes greater than or equal to 2, after they have won more than 11 games. So, the logic should have been like this
if (pointsA >= 11) and (pointsA - pointsB >= 2):
...
elif (pointsB >= 11) and (pointsB - pointsA >= 2):
...
I think your code is running infinitely.
Consider: pointsA and pointsB reach 10 and 10 respectively. Now, no matter what player gets the next point, neither of your terminating conditions will be reached because neither pointsA nor pointsB will be 11 and up by 2 at the same time. This creates an infinite loop.
You'd probably want to check if pointsA >= 11 and pointsB >= 11 instead of A == 11 and B == 11.
Looks like thefourtheye beat me by a bit - he gets my vote.
I am VERY new to Python and I have to create a game that simulates flipping a coin and ask the user to enter the number of times that a coin should be tossed. Based on that response the program has to choose a random number that is either 0 or 1 (and decide which represents “heads” and which represents “tails”) for that specified number of times. Count the number of “heads” and the number of “tails” produced, and present the following information to the user: a list consisting of the simulated coin tosses, and a summary of the number of heads and the number of tails produced. For example, if a user enters 5, the coin toss simulation may result in [‘heads’, ‘tails’, ‘tails’, ‘heads’, ‘heads’]. The program should print something like the following: “ [‘heads’, ‘tails’, ‘tails’, ‘heads’, ‘heads’]
This is what I have so far, and it isn't working at all...
import random
def coinToss():
number = input("Number of times to flip coin: ")
recordList = []
heads = 0
tails = 0
flip = random.randint(0, 1)
if (flip == 0):
print("Heads")
recordList.append("Heads")
else:
print("Tails")
recordList.append("Tails")
print(str(recordList))
print(str(recordList.count("Heads")) + str(recordList.count("Tails")))
You need a loop to do this. I suggest a for loop:
import random
def coinToss():
number = input("Number of times to flip coin: ")
recordList = []
heads = 0
tails = 0
for amount in range(number):
flip = random.randint(0, 1)
if (flip == 0):
print("Heads")
recordList.append("Heads")
else:
print("Tails")
recordList.append("Tails")
print(str(recordList))
print(str(recordList.count("Heads")) + str(recordList.count("Tails")))
I suggest you read this on for loops.
Also, you could pass number as a parameter to the function:
import random
def coinToss(number):
recordList, heads, tails = [], 0, 0 # multiple assignment
for i in range(number): # do this 'number' amount of times
flip = random.randint(0, 1)
if (flip == 0):
print("Heads")
recordList.append("Heads")
else:
print("Tails")
recordList.append("Tails")
print(str(recordList))
print(str(recordList.count("Heads")) + str(recordList.count("Tails")))
Then, you need to call the function in the end: coinToss().
You are nearly there:
1) You need to call the function:
coinToss()
2) You need to set up a loop to call random.randint() repeatedly.
I'd go with something along the lines of:
from random import randint
num = input('Number of times to flip coin: ')
flips = [randint(0,1) for r in range(num)]
results = []
for object in flips:
if object == 0:
results.append('Heads')
elif object == 1:
results.append('Tails')
print results
This is possibly more pythonic, although not everyone likes list comprehensions.
import random
def tossCoin(numFlips):
flips= ['Heads' if x==1 else 'Tails' for x in [random.randint(0,1) for x in range(numflips)]]
heads=sum([x=='Heads' for x in flips])
tails=numFlips-heads
import random
import time
flips = 0
heads = "Heads"
tails = "Tails"
heads_and_tails = [(heads),
(tails)]
while input("Do you want to coin flip? [y|n]") == 'y':
print(random.choice(heads_and_tails))
time.sleep(.5)
flips += 1
else:
print("You flipped the coin",flips,"times")
print("Good bye")
You could try this, i have it so it asks you if you want to flip the coin then when you say no or n it tells you how many times you flipped the coin. (this is in python 3.5)
Create a list with two elements head and tail, and use choice() from random to get the coin flip result. To get the count of how many times head or tail came, append the count to a list and then use Counter(list_name) from collections. Use uin() to call
##coin flip
import random
import collections
def tos():
a=['head','tail']
return(random.choice(a))
def uin():
y=[]
x=input("how many times you want to flip the coin: ")
for i in range(int(x)):
y.append(tos())
print(collections.Counter(y))
Instead of all that, you can do like this:
import random
options = ['Heads' , 'Tails']
number = int(input('no.of times to flip a coin : ')
for amount in range(number):
heads_or_tails = random.choice(options)
print(f" it's {heads_or_tails}")
print()
print('end')
I did it like this. Probably not the best and most efficient way, but hey now you have different options to choose from. I did the loop 10000 times because that was stated in the exercise.
#Coinflip program
import random
numberOfStreaks = 0
emptyArray = []
for experimentNumber in range(100):
#Code here that creates a list of 100 heads or tails values
headsCount = 0
tailsCount = 0
#print(experimentNumber)
for i in range(100):
if random.randint(0, 1) == 0:
emptyArray.append('H')
headsCount +=1
else:
emptyArray.append('T')
tailsCount += 1
#Code here that checks if the list contains a streak of either heads or tails of 6 in a row
heads = 0
tails = 0
headsStreakOfSix = 0
tailsStreakofSix = 0
for i in emptyArray:
if i == 'H':
heads +=1
tails = 0
if heads == 6:
headsStreakOfSix += 1
numberOfStreaks +=1
if i == 'T':
tails +=1
heads = 0
if tails == 6:
tailsStreakofSix += 1
numberOfStreaks +=1
#print('\n' + str(headsStreakOfSix))
#print('\n' + str(tailsStreakofSix))
#print('\n' + str(numberOfStreaks))
print('\nChance of streak: %s%%' % (numberOfStreaks / 10000))
#program to toss the coin as per user wish and count number of heads and tails
import random
toss=int(input("Enter number of times you want to toss the coin"))
tail=0
head=0
for i in range(toss):
val=random.randint(0,1)
if(val==0):
print("Tails")
tail=tail+1
else:
print("Heads")
head=head+1
print("The total number of tails is {} and head is {} while tossing the coin {} times".format(tail,head,toss))
Fixing the immediate issues
The highest voted answer doesn't actually run, because it passes a string into range() (as opposed to an int).
Here's a solution which fixes two issues: the range() issue just mentioned, and the fact that the calls to str() in the print() statements on the last two lines can be made redundant. This snippet was written to modify the original code as little as possible.
def coinToss():
number = int(input("Number of times to flip coin: "))
recordList = []
heads = 0
tails = 0
for _ in range(number):
flip = random.randint(0, 1)
if (flip == 0):
recordList.append("Heads")
else:
recordList.append("Tails")
print(recordList)
print(recordList.count("Tails"), recordList.count("Heads"))
A more concise approach
However, if you're looking for a more concise solution, you can use a list comprehension. There's only one other answer that has a list comprehension, but you can embed the mapping from {0, 1} to {"Heads", "Tails"} using one, rather than two, list comprehensions:
def coinToss():
number = int(input("Number of times to flip coin: "))
recordList = ["Heads" if random.randint(0, 1) else "Tails" for _ in range(number)]
print(recordList)
print(recordList.count("Tails"), recordList.count("Heads"))
import random
def coinToss(number):
heads = 0
tails = 0
for flip in range(number):
coinFlip = random.choice([1, 2])
if coinFlip == 1:
print("Heads")
recordList.append("Heads")
else:
print("Tails")
recordList.append("Tails")
number = input("Number of times to flip coin: ")
recordList = []
if type(number) == str and len(number)>0:
coinToss(int(number))
print("Heads:", str(recordList.count("Heads")) , "Tails:",str(recordList.count("Tails")))
All Possibilities in Coin Toss for N number of Coins
def Possible(n, a):
if n >= 1:
Possible(n // 2, a)
z = n % 2
z = "H" if z == 0 else "T"
a.append(z)
return a
def Comb(val):
for b in range(2 ** N):
A = Possible(b, [])
R = N - len(A)
c = []
for x in range(R):
c.append("H")
Temp = (c + A)
if len(Temp) > N:
val.append(Temp[abs(R):])
else:
val.append(Temp)
return val
N = int(input())
for c in Comb([]):
print(c)
heads = 1
tails = 0
input("choose 'heads' or 'tails'. ").upper()
random_side = random.randint(0, 1)
if random_side == 1:
print("heads you win")
else:
print("sorry you lose ")