trying to +1 to random.seed() for every loop - python

I'm working on a casino program that gets a bet ($1-$50) from the user, then pulls a slot machine to display a three-string combination of "7", "cherries", "bar", or "(space)". Certain combinations will trigger a bet multiplier, and the user will win back this amount. The run should look like this: ask user for bet, show user the pull and their winnings, then ask user for a new bet, display a new pull, and so on.
Right now, I have everything down except for a couple problems - I cannot make it so that the program generates a new random combination for each pull. Secondly, the main loop continues forever, printing the user's pull and winnings forever. Below is the method that generates either "7", "cherries", etc.
def rand_string(self):
random.seed(0)
# produces a number between 0 and 999
test_num = random.randrange(1000)
# precompute cutoffs
bar_cutoff = 10 * TripleString.BAR_PCT
cherries_cutoff = bar_cutoff + 10 * TripleString.CHERRIES_PCT
space_cutoff = cherries_cutoff + 10 * TripleString.SPACE_PCT
# bar = 38%, cherries = 40%, space = 7%, seven = 15%
if test_num < bar_cutoff:
return TripleString.BAR
elif test_num < cherries_cutoff:
return TripleString.CHERRIES
elif test_num < space_cutoff:
return TripleString.SPACE
else:
return TripleString.SEVEN
And here is the loop in main:
while(True):
if bet == 0: #a bet of $0 ends the program
print("Please come again!")
break
else:
print("whirrr...and your pull is " +\
object.pull())
object.display(None)
I thought I could solve this by somehow adding 1 to random.seed() for each loop (we begin with random.seed(0), but for each new pull 1 is added so that random.seed(1) and so on), but I don't know how to go about doing this and I'm not even sure if it's doable. If someone could point out my mistakes here, that'd be great. (sorry if this makes no sense, I'm very new to Python).

You should only call random.seed(0) once in the program. By seeding every time you are reseting the pseudo random number generator and forcing it to produce the same number.
random.seed(0)
while(True):
if bet == 0: #a bet of $0 ends the program
...
You can read more about random seeding here.

Related

while loop wont stop running in python

I am working on a crash game in python and im trying to make it crash when a value hits 1,50, or 100 but it keeps going. Does anyone know why?
import random
import time
game = 1
num = 1.00
while game == 1:
num += .01
print(round(num, 2))
time.sleep(.1)
if game != 1:
print("Crash!")
break
while game == 1:
crash = random.randint(1, 100)
time.sleep(.1)
if crash == 1 or crash == 50 or crash == 100:
game -= 1
else:
break
In first while loop game's value never changes from 1 therefore never exits the first while loop
BTW you do not have to break the loop because once game != 1 it will won't enter the loop again.
I think you mean to use only the second while loop you have written - so you can delete the first one and remove the else from the second - no need for it for the same reason you do not need the break in the first loop.
so if I understand your intention correctly than the code should be:
import time
game = 1
while game == 1:
crash = random.randint(1, 100)
time.sleep(.1)
if crash == 1 or crash == 50 or crash == 100:
game -= 1
If you're new to computer science, it can sometimes be useful to "play computer" when looking at code. Look at each step of the code and try to imagine what would happen. In a language like python, you can even test these statements one at a time to make sure they do what you think they do.
Let's skip to the important part.
The state of the memory is game and num both equal 1.
while game == 1: # loop until game is not 1
num += .01 # add 0.01 to num
print(round(num, 2)) #print round(num, 2); 1.01 the first time
time.sleep(.1) # sleep for 1 10th of a second
if game != 1: #game was not changed before this point, so game=1
print("Crash!") # this will never execute, ignore it.
break
# End of the loop: execution flow return to the start again, with num=1.01
You see the problem? This will never exit because game is never altered in the loop, this will continue to loop forever. The second loop won't ever even be reached because it's going to be stuck in the first one.

How can I create a function to calculate the win percentage of a game as you play more games?

I have been trying to create a function to do this as practice. I haven't been coding for long at all. I have tried many things but my current piece of code is as follows:
print("If win, type 1. If lose, type 0")
result_list = []
result = input("game result? ")
if result == 1:
result_list.append(1)
else:
result_list.append(0)
percent = (sum(result_list)/len(result_list)) * 100
print("the win percentage is",percent,"%")
I would like to be able to input the number 1 for a win and have this add to the currently empty list. At the moment the result will always come out as 0%. Am I just doing everything wrong?
Code example:
results = []
for _ in range(10):
result_list.append(int(input("game result? ")))
percent = (sum(result_list)/len(result_list)) * 100
print("the win percentage is",percent,"%")
You can move the 2 last lines & change the 10 from the for loop to see the effect of a for loop ;)

How do I stop a while loop if something happens inside a function that should stop the itterations?

Hello fellow programmers! I am a beginner to python and a couple months ago, I decided to start my own little project to help my understanding of the whole development process in Python. I briefly know all the basic syntax but I was wondering how I could make something inside a function call the end of the while loop.
I am creating a simple terminal number guessing game, and it works by the player having several tries of guessing a number between 1 and 10 (I currently made it to be just 1 to test some things in the code).
If a player gets the number correct, the level should end and the player will then progress to the next level of the game. I tried to make a variable and make a true false statement but I can't manipulate variables in function inside of a while loop.
I am wondering how I can make it so that the game just ends when the player gets the correct number, I will include my code down here so you guys will have more context:
import random
import numpy
import time
def get_name(time):
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
# The Variable 'tries' is the indication of how many tries you have left
tries = 1
while tries < 6:
def try_again(get_number, random, time):
# This is to ask the player to try again
answer = (input(" Do you want to try again?"))
time.sleep(2)
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
else:
print("Thank you for playing the game, I hope you have better luck next time")
def find_rand_num(get_number, random, time):
num_list = [1,1]
number = random.choice(num_list)
# Asks the player for the number
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
try_again(get_number, random, time)
def get_number(random, try_again, find_rand_num, time):
# This chooses the number that the player will have to guess
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
find_rand_num(get_number, random, time)
if tries < 2:
get_name(time)
tries += 1
get_number(random, try_again, find_rand_num, time)
else:
tries += 1
get_number(random, try_again, find_rand_num, time)
if tries > 5:
break
I apologize for some of the formatting in the code, I tried my best to look as accurate as it is in my IDE. My dad would usually help me with those types of questions but it appears I know more python than my dad at this point since he works with front end web development. So, back to my original question, how do I make so that if this statement:
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
is true, the while loop ends? Also, how does my code look? I put some time into making it look neat and I am interested from an expert's point of view. I once read that in programming, less is more, so I am trying to accomplish more with less with my code.
Thank you for taking the time to read this, and I would be very grateful if some of you have any solutions to my problem. Have a great day!
There were too many bugs in your code. First of all, you never used the parameters you passed in your functions, so I don't see a reason for them to stay there. Then you need to return something out of your functions to use them for breaking conditions (for example True/False). Lastly, I guess calling functions separately is much more convenient in your case since you need to do some checking before proceeding (Not inside each other). So, this is the code I ended up with:
import random
import time
def get_name():
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
def try_again():
answer = (input("Do you want to try again? "))
time.sleep(2)
# Added return True/False to check whether user wants to play again or not
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
return True
else:
print("Thank you for playing the game, I hope you have better luck next time")
return False
# Joined get_number and find_random_number since get_number was doing nothing than calling find_rand_num
def find_rand_num():
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
num_list = [1,1]
number = random.choice(num_list)
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
# Added return to check if correct answer is found or not
return "Found"
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
tries = 1
while tries < 6:
if tries < 2:
get_name()
res = find_rand_num()
if res == "Found":
break
checker = try_again()
if checker is False:
break
# Removed redundant if/break since while will do it itself
tries += 1

Python Monty hall n number of doors

I have a model of the Monty Hall program running but I need to figure out how to ask the user for the number of doors of in this case, hiding places. The code for the simulation works, it's just the starting section I need help with. This is what I have so far, thanks for any help in advance.
import random
#Ask the user for how many runs to simumlate
runs = int(input("How many games do you want to simulate?"))
switchwins, nonswitchwins, switchlosses, nonswitchlosses = 0, 0, 0, 0
# Get the random number started with a seed
random.seed()
#run once for user switching and once for user not switching
for swap in True,False:
# Do everything for the number of runs we have
for i in range(runs):
#Ask the user for the number of hiding places which must be greater than 3
while True:
hidingplaces = int(input("This game requires 3 or more hiding places. How many would you like?"))
if hidingplaces < 3:
#return error
raise ValueError(f'doors must be greater than three, not {hidingplaces}')
else:
break
# All prizes are nothing apart from one which holds the coin
prizes = ['nothing', 'nothing', 'coin']
# Randomly mix them up
random.shuffle(prizes)
#select a random location
ChoiceA = random.randrange(hidingplaces)
# print("Before the prize is revealed, I will show you what is in one of the other hiding places")
# remove one of the other hiding places which has nothing as a prize and isn't ChoiceA
for currentlocation, contents in enumerate(prizes):
if currentlocation != ChoiceA and contents == "nothing":
showlocation = currentlocation
# print("There is nothing in this location", showlocation)
break
if swap:
#swap to the other location
for currentlocation, contents in enumerate(prizes):
if currentlocation != ChoiceA and currentlocation != showlocation:
swap_to = currentlocation
# check if the swapped choice is a win
if prizes[swap_to] == "coin":
switchwins +=1
else:
switchlosses +=1
# when not swapping locations check for win
else:
if prizes[ChoiceA] == "coin":
nonswitchwins +=1
else:
nonswitchlosses +=1
print("This is the number of wins if the user switched", round((switchwins/runs)*100,1), "%")
print("This is the number of wins if the user didn't switch", round((nonswitchwins/runs)*100,1),"%")
The error I'm getting is:
IndexError Traceback (most recent call last)
<ipython-input-15-e7e700a3b515> in <module>()
57 # when not swapping locations check for win
58 else:
---> 59 if prizes[ChoiceA] == "coin":
60 nonswitchwins +=1
61 else:
IndexError: list index out of range
The problem you're reporting is not, after all, with the user input routine. It is that you are allowing the user to specify hidingplaces > 3 while at the same time hardcoding the list prizes to have exactly 3 entries. ChoiceA, which can be (randomly) set to any number less than hidingplaces, is used as an index into prizes. It raises the exception you report whenever ChoiceA happens to be greater than 2.
Strategies to fix this might include (a) making use of the value of hidingplaces when you define the list of prizes or (b) using ChoiceA % len(prizes) as the index into prizes instead of just ChoiceA. Note that these have different effects on the statistical behavior of the simulation: the correct choice depends on how you want it to behave. From the comment next to your existing definition of prizes, this definition is probably what you intend:
prizes = [ 'coin' ] + [ 'nothing' ] * ( hidingplaces - 1 )
I have fixed your code. I rewrote it and simplified it, fixed some syntax errors, and fixed some indent errors.
Check the comments in the code.
EDIT: I have fixed the code.
def askDoors():
'''
Ask the user for the number of hiding places which must be greater than 3
'''
return int(input("This game requires 3 or more hiding places. How many would you like?"))
hidingplaces = askDoors()
while hidingplaces < 3:
# return error
print('Doors must be greater than three, not %d.' % hidingplaces)
hidingplaces = askDoors()
print('Start.') # put game here (recommended to use a function)
EDIT: For the second problem, just change prizes to prizes = ['coin'] and add this right after it.
for i in range(hidingplaces):
prizes.append('nothing')

Loop and validation in number guessing game

I have previously studied Visual Basic for Applications and am slowly getting up to speed with python this week. As I am a new programmer, please bear with me. I understand most of the concepts so far that I've encountered but currently am at a brick wall.
I've written a few functions to help me code a number guessing game. The user enters a 4 digit number. If it matches the programs generated one (I've coded this already) a Y is appended to the output list. If not, an N.
EG. I enter 4567, number is 4568. Output printed from the list is YYYN.
import random
def A():
digit = random.randint(0, 9)
return digit
def B():
numList = list()
for counter in range(0,4):
numList.append(A())
return numList
def X():
output = []
number = input("Please enter the first 4 digit number: ")
number2= B()
for i in range(0, len(number)):
if number[i] == number2[i]:
results.append("Y")
else:
results.append("N")
print(output)
X()
I've coded all this however theres a few things it lacks:
A loop. I don't know how I can loop it so I can get it to ask again. I only want the person to be able to guess 5 times. I'm imagining some sort of for loop with a counter like "From counter 1-5, when I reach 5 I end" but uncertain how to program this.
I've coded a standalone validation code snippet but don't know how I could integrate this in the loop, so for instance if someone entered 444a it should say that this is not a valid entry and let them try again. I made an attempt at this below.
while myNumber.isnumeric() == True and len(myNumber) == 4:
for i in range(0, 4)):
if myNumber[i] == progsNumber[i]:
outputList.append("Y")
else:
outputList.append("N")
Made some good attempts at trying to work this out but struggling to patch it all together. Is anyone able to show me some direction into getting this all together to form a working program? I hope these core elements that I've coded might help you help me!
To answer both your questions:
Loops, luckily, are easy. To loop over some code five times you can set tries = 5, then do while tries > 0: and somewhere inside the loop do a tries -= 1.
If you want to get out of the loop ahead of time (when the user answered correctly), you can simply use the break keyword to "break" out of the loop. You could also, if you'd prefer, set tries = 0 so loop doesn't continue iterating.
You'd probably want to put your validation inside the loop in an if (with the same statements as the while loop you tried). Only check if the input is valid and otherwise continue to stop with the current iteration of your loop and continue on to the next one (restart the while).
So in code:
answer = [random.randint(0, 9) for i in range(4)]
tries = 5
while tries > 0:
number = input("Please enter the first 4 digit number: ")
if not number.isnumeric() or not len(number) == len(answer):
print('Invalid input!')
continue
out = ''
for i in range(len(answer)):
out += 'Y' if int(number[i]) == answer[i] else 'N'
if out == 'Y' * len(answer):
print('Good job!')
break
tries -= 1
print(out)
else:
print('Aww, you failed')
I also added an else after the while for when tries reaches zero to catch a failure (see the Python docs or maybe this SO answer)

Categories