Need help fixing random number - python

I'm learning Python and was working on the random dice throw. When I run it, it repeats the same number that is first shown after asked if you want to play again. I need help finding where I'm going wrong here.
I've tried moving code around and also putting different varieties of the code. I'm just stumped.
import sys
import random
import time
greeting = "Welcome to my Dice Game!"
roll = "Lets roll this die!"
die = random.randint(0, 6)
print(greeting)
time.sleep(2)
answer = input("Want to play?")
while answer == "yes" or answer == "y":
print(roll)
time.sleep(2)
print(die)
answer = input("Want to play again?")
print("Thanks for playing!")
This is what I get:
Welcome to my Dice Game!
Want to play?yes
Lets roll this die!
5
Want to play again?yes
Lets roll this die!
5
Want to play again?y
Lets roll this die!
5

You need to recompute the value of the dice each time in your loop like:
import sys
import random
import time
greeting = "Welcome to my Dice Game!"
roll = "Lets roll this die!"
print(greeting)
time.sleep(2)
answer = input("Want to play?")
while answer == "yes" or answer == "y":
print(roll)
time.sleep(2)
die = random.randint(0, 6) # recompute it here instead
print(die)
answer = input("Want to play again?")
print("Thanks for playing!")

When you run the command die = random.randint(0, 6), what you're telling Python is "Use the random.randint() function to pick a random integer between 1 and 6, and then set the variable named die equal to the integer that got chosen". Once that's done, the rest of your code doesn't do anything to update the value of die. This means print(die) within the loop is just going to keep printing whatever value it was initially given. In other words, the command die = random.randint(0, 6) doesn't mean "Re-run the command random.randint(0, 6) and get another random number each and every time I refer to die". Rather, die is just some variable with a specific, constant value.
Since random.randint() is what does the actual number generation, one way to keep updating die is to simply move the command you have outside of the loop to the inside of the loop:
while answer == "yes" or answer == "y":
print(roll)
die = random.randint(0, 6) # Generate a new random number, then assign it to 'die'
time.sleep(2)
print(die)
answer = input("Want to play again?")
In fact, if you aren't really doing anything with the number other than printing it, you could forget using a variable altogether and just stick the random.randint() command inside of your print command:
while answer == "yes" or answer == "y":
print(roll)
time.sleep(2)
print(random.randint(0, 6))
answer = input("Want to play again?")

Related

Why does my code make me type "yes" or "no" twice to get the result I want instead of just once?

Why does this code make me type yes or no twice to get the result I want instead of just once?
This is for the python dice roll text game, btw...
import random
min = 1
max = 20
# <!--TWO D-20's, A-LA DUNGEONS AND DRAGAONS--!>
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print("Rolling the dice")
print("The values are --- ")
print(random.randint(min, max))
print(random.randint(min, max))
roll_again = input("Would you like to play again?")
answer = input()
if answer == ('yes'):print("OK, here we go!")
elif answer == ("no"):print("Sorry about that, please try again another time.")
I am entering into a python class on Monday, this is one of the more common types of beginners code (granted I spiced it up by changing the dice from 6 sided to 20 sided, but it's more fun that way...lol) that I have read in some of the python books and sites I have visited, so I wanted to kind of get my feet wet a bit before I start my class.
So, any idea why I have to type yes or no twice, hitting enter after each time, to get it to run properly?
For the record, I am on Win10 right now but I also mostly use Parrot Security OS (Linux)...
Thanks for any and all feedback which anyone can provide...I know it's probably a stupid noob mistake or oversight, since I don't really know or understand the basics, but the quicker I can grasp them the better...
Python's function input() asks for users to input and waits the answer. As it can be seen in your code, you're doing it two times:
roll_again = input("Would you like to play again?")
answer = input()
The variable roll_again is being redeclarated to the first user's input, then the variable answer is getting the second user's input. You maybe meant to do something like:
roll_again = input("Would you like to play again?")
answer = roll_again
But first of all, there is no need to create an answer variable, you could simply use the roll_again on the if. Also the if statement is out of the while so your code might not work as you're trying to anyways~ (it will re-roll if user inputs yes but it will not print the message you're trying to; that will only happen when the user inputs no as that will go out of the while and blah blah blah)
This should be alright:
import random
min = 1
max = 20
# <!--TWO D-20's, A-LA DUNGEONS AND DRAGAONS--!>
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print("Rolling the dice")
print("The values are --- ")
print(random.randint(min, max))
print(random.randint(min, max))
roll_again = input("Would you like to play again?")
if roll_again == 'yes' or roll_again == 'y': print("OK, here we go!")
else: print("Sorry about that, please try again another time.")
Every time you call the input() function, it prompts for input. Since you call it twice for each iteration of your while loop, the user is prompted twice per iteration. You should instead only call the input() function once in your while loop.
You can also avoid using the answer variable if you just use the roll_again variable for your conditions for your if and elif.

Force Python code to restart itself properly

I have tried to figure out a way on how to restart my code in Python, but I can't get it to work properly.
if keepLooping == True:
if userInput == randomNumber:
if attempt == 1:
print()
print("Correct, First try!")
stop = time.time()
print("It took", int(stop - start), "seconds.")
replay = input("Do you want to play again?: ")
if replay.lower() in ("yes"):
print()
os.execl(sys.executable, '"{}"'.format(sys.executable), *sys.argv) # Restart code. You are here
elif replay.lower() in ("no"):
break
else:
print("Invalid input, Yes or No?")
continue # Restart segment. You are here
replayAttempt += 1
print()
As you can see, I have tried using os.execl(sys.executable, '"{}"'.format(sys.executable), *sys.argv). Sure, it works, but then one of my inputs turn red, as you can see here. I have been trying to solve this but I can't find a solution.
I found a solution for the text being red, I added '\033[37m' before my inputs. The only problem I have now is that it can only restart once. When I try it again I get this error code here.
One way to this is to encapsulate thing into function
going from this
#start of scrip
#... game logic
#end of script
to
def game():
#...game logic
game()
encapsulated like this allow for easier reuse of stuff, and allow you to reduce repetition, if you do same thing in your code two or more times that is when you should factor that out into its own function, that is the DRY principle, Don't Repeat Yourself.
You can do something like this for example
def game():
#...game logic
return game_result
def main():
done=False
result=[]
while not done:
result.append( game() )
reply = input("Do you want to play again?: ")
if reply=="no":
done=True
#display the result in a nice way
main()
Here the main function do a couple of simple thing, play one round of the game, save the result, ask if you want to play again and display the result, and the game function do all the heavy work of playing the game.
Here is a simple working example of guess the number between 0 and 10
import random
def game(lower,upper):
answer = str(random.randint(lower, upper))
user_answer = input(f"Guess a number between {lower} and {upper}: ")
game_result = user_answer == answer
if game_result:
print("you win")
else:
print("you lose, the answer was:",answer)
return game_result
def main(lower=0,upper=10):
done=False
result=[]
while not done:
result.append( game(lower,upper) )
reply = input("Do you want to play again?: ")
if reply=="no":
done=True
print("Your result were",sum(result),"/",len(result) )
main()
Notice that the game function take 2 arguments, so you can play this game not just with 0 and 10, but any two number you desire, in turn the main function also take those same arguments but assign them default value so if you don't call this function with any of them it will use those default value and use them to call the game function, doing so allow for flexibility that you wouldn't have if you lock it to just 0 and 10 in this case.
(the sum(result) is because boolean are a subclass of int(numbers) so in math operation they are True==1 and False==0)

Continue outside of loop, dice rolling script

I'm making a dice rolling game. The following code produces an error, saying "continue outside of loop":
import random
repeat="y" or "yes"
while repeat == "y" or "yes"
print("Rolling the dice")
print(random.randint(1,6))
repeat = input("Do you wanna roll again Y/N?").lower()
if repeat =="y" or "yes":
continue
else:
print("Thanks for rolling")
break
Why am I getting this error?
You cannot affect 2 walues as teh same time, chose "y" or "Y" in your expressions.
repeat="y"
while (repeat == "y") or (repeat == "yes"):
You have to check your indentation too,
repeat = input has to be inside the loop, so you get a new input to check each time.
The final print can be put outside the loop at the very end.
Here is a working example, and you can type anything starting with "y"/"Y" to continue rolling:
import random
repeat="y"
while (repeat[0]) == "y":
print("Rolling the dice")
print(random.randint(1,6))
repeat = input("Do you wanna roll again Y/N?").lower()
print("Thanks for rolling")

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

How do I make this dice game run in a simulation 10,000 times using python?

I'm doing a homework assignment. I can't seem to find a solution on how to make the dice roll 10,000 times plus create a variable that updates everytime you win some money when you roll the dice correctly. I have some instructions on the homework below can anyone shed some light on me?
The game is played as follows: roll a six sided die.
If you roll a 1, 2 or a 3, the game is over.
If you roll a 4, 5, or 6, you win that many dollars ($4, $5, or $6), and then roll again.
With each additional roll, you have the chance to win more money, or you might roll a game-ending 1, 2, or 3, at which time the game is over and you keep whatever winnings you have accumulated.
Use the randint function from Python's Random module to get a die roll result
(see functions for integers).
Run 10,000 simulations of the game (Monte Carlo method).
Print the average amount won and the largest amount won.
Just as a thought experiment, would you pay $3 for a chance to play this game?
Example Output:
Average amount won = x.xx
Max amount won = xx
import random
class diceGame:
def __init__(self,dice):
self.dice = dice
def gameOutCome(self):
askUser = str(input("Roll to play the game? Y/N: "))
while True:
if askUser == 'y':
print(self.dice)
if self.dice == 1:
print("Sorry, Try Again!")
elif self.dice == 2:
print("Sorry, Try Again!")
elif self.dice == 3:
print("Sorry, Try Again!")
elif self.dice == 4:
print("You win $4")
elif self.dice == 5:
print("You win $5")
elif self.dice == 6:
print("You win $6")
askUser = str(input("Roll to play the game? Y/N: "))
x = random.randint(1,6)
dd = diceGame(x)
dd.gameOutCome()
Welcome to stackoverflow. Since this is your homework, I don't think it is appropriate to post an entire solution here.
However I do think some pointers in the right direction might be helpful:
1) You are running the simulation 10000 times. Each roll requires 2 user inputs. So in order to finish the simulation you need at least 20000 user inputs... Yeah that will be tiresome ;) .... So lets cut the user input - just write a function that executes the game until the game is finished. Once you have a function that executes one game, how can you execute it multiple times?
2) Think of each roll having two possible outcomes - continue the game or not. What des it mean to continue? What condition has to be fullfilled for the game to end?
3) Once the game has ended, what do you need to do with the money?
4) You can use the sum and max functions to calculate the average and the maximum win.
import random
def play_game():
#The function that executes the game - you have to write that on your own
pass
wins = [play_game() for i in range(0,10000)]
win_average = sum(wins)/10000.0
max_win = max(wins)

Categories