I have been working on this guessing game but i just cant get it to repeat the game when the player says yes. The game gives you 5 attempts to guess the number that it thought of and then after it asks you if you would like to play again but when you say 'YES' it just keeps repeating the sentence and when you say 'NO' it does what its supposed to which is break the code
def main():
game = "your game"
print(game)
play_again()
import random #imports random number function
print("Welcome to the number guessing game!")
counter=1 #This means that the score is set to 0
number = int(random.randint(1,10))
while counter >0 and counter <=5:
guess=int(input("Try and guess the number\n"))#tells the user to try and guess the number
if guess!=number and guess>number:
print("wrong number! Try again you are too high")#tells you that you were wrong and that that you were too high
counter=counter+1#adds 1 count for every attempt it took you to guess the number
elif guess!=number and guess<number:
print("wrong number! Try again you are too low!")#tells you that you were wrong and tells you that you were too low
counter=counter+1#adds 1 count for every attempt it took you to guess the number
else:
print("Well done! You have guessed the number i was thinking of! The number was ",number)#Prints this out when you guessed the number
print("it took you ",counter, "attempts!")#tells you how many attempts it took you to guess the number
if counter==2:
print("4 attempts left before program ends")
if counter==3:
print("3 attempts left before program ends")
if counter==4:
print("2 attempts left before program ends")
if counter==5:
print("1 attempts left before program ends")
def play_again():
while True:
play_again = input("Would you like to play again?(yes or no) : ")
if play_again == "yes":
main()
if play_again == "no":
exit()
else:
print("I'm sorry I could not recognize what you entered")
main()
It's because your game code isn't in the function. Try it in this manner:
<import statements>
def game():
<insert all game code>
def main():
while True:
play_again = input("Would you like to play again?(yes or no) : ")
if play_again == "yes":
game()
if play_again == "no":
exit()
else:
print("I'm sorry I could not recognize what you entered")
There's a few problems with your code that I'd like to point out.
The main one being that your game does not run again when typing yes. All it will do is run main() which will print your game and then ask you if you want to retry once again. It's easier if you put your game inside a definition that way you can call it whenever necessary.
Also, I don't know if it's just me, but if you guess the correct number, it will still ask you to guess a number. You need to exit your loop by putting your play_again() method in your else block.
Below is the code. I've polished it up a little just for optimization.
import random #imports random number function
def main():
print("Welcome to the number guessing game!")
game = "your game"
print(game)
run_game()
play_again()
def run_game():
counter = 1
number = random.randint(1, 10)
while counter > 0 and counter <= 5:
guess=int(input("Try and guess the number\n"))#tells the user to try and guess the number
if guess!=number and guess > number:
print("wrong number! Try again you are too high")#tells you that you were wrong and that that you were too high
counter=counter+1#adds 1 count for every attempt it took you to guess the number
elif guess != number and guess < number:
print("wrong number! Try again you are too low!")#tells you that you were wrong and tells you that you were too low
counter=counter+1#adds 1 count for every attempt it took you to guess the number
else:
print("Well done! You have guessed the number i was thinking of! The number was " + str(number))#Prints this out when you guessed the number
print("it took you " + str(counter) + " attempts!")#tells you how many attempts it took you to guess the number
play_again()
if counter == 2:
print("4 attempts left before program ends")
if counter == 3:
print("3 attempts left before program ends")
if counter == 4:
print("2 attempts left before program ends")
if counter == 5:
print("1 attempts left before program ends")
def play_again():
while True:
retry = input("Would you like to play again?(yes or no) : ")
if retry == "yes":
main()
if retry == "no":
exit()
else:
print("I'm sorry I could not recognize what you entered")
main()
Related
I am making a program that generates a random number and asks you to guess the number out of the range 1-100. Once you put in a number, it will generate a response based on the number. In this case, it is Too high, Too low, Correct, or Quit too soon if the input is 0, which ends the program(simplified, but basically the same thing).
It counts the number of attempts based on how many times you had to do the input function, and it uses a while loop to keep asking for the number until you get it correct. The problem that I am facing is that I have to make it break out of the while loop once the guess is either equal to the random number or 0. This normally isn't an issue, because you could use sys.exit() or some other function, but according to the instructions I can't use break, quit, exit, sys.exit, or continue. The problem is most of the solutions I've found for breaking the while loop implement break, sys.exit, or something similar and I can't use those. I used sys.exit() as a placeholder, though, so that it would run the rest of the code, but now I need to figure out a way to break the loop without using it. This is my code:
import random
import sys
def main():
global attempts
attempts = 0
guess(attempts)
keep_playing(attempts)
def guess(attempts):
number = random.randint(1,100)
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
while guess != 0:
if guess != number:
if guess < number:
print("Too low, try again")
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
elif guess > number:
print("Too high, try again")
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
else:
print()
print("Congratulations! You guessed the right number!")
print("There were", attempts,"attempts")
print()
#Ask if they want to play again
sys.exit()#<---- using sys.exit as a placeholder currently
else:
print()
print("You quit too early")
print("The number was ",number,sep='')
#Ask if they want to play again
sys.exit()#<----- using sys.exit as a placeholder currently
def keep_playing(attempts):
keep_playing = 'y'
if keep_playing == 'y' or keep_playing == 'n':
if keep_playing == 'y':
guess(attempts)
keep_playing = input("Another game (y to continue)? ")
elif keep_playing == 'n':
print()
print("You quit too early")
print("Number of attempts", attempts)
main()
If anyone has any suggestions or solutions for how to fix this, please let me know.
Try to implement this solution to your code:
is_playing = True
while is_playing:
if guess == 0:
is_playing = False
your code...
else:
if guess == number:
is_playing = False
your code...
else:
your code...
Does not use any break etc. and It does breaks out of your loop as the loop will continue only while is_playing is True. This way you will break out of the loop when the guess is 0 (your simple exit way) or when the number is guessed correctly. Hope that helps.
I am not a fan of global variables but here it's your code with my solution implemented:
import random
def main() -> None:
attempts = 0
global is_playing
is_playing = True
while is_playing:
guess(attempts)
keep_playing()
def guess(attempts: int) -> None:
number = random.randint(1,100)
print(number)
is_guessing = True
while is_guessing:
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
if guess == 0:
is_guessing = False
print("\nYou quit too early.")
print("The number was ", number,sep='')
else:
if guess == number:
is_guessing = False
print("\nCongratulations! You guessed the right number!")
print("There were", attempts, "attempts")
else:
if guess < number:
print("Too low, try again.")
elif guess > number:
print("Too high, try again.")
def keep_playing() -> None:
keep_playing = input('Do you want to play again? Y/N ')
if keep_playing.lower() == 'n':
global is_playing
is_playing = False
main()
TIP:
instead
"There were", attempts, "attempts"
do: f'There were {attempts} attempts.'
I'm making a guessing game, but I want to add another line of code where the user can play again after, but I don't know where to start.
print ("Welcome to the Number Guessing Game in Python!")
# Initialize the number to be guessed
number_to_guess = 7
# Initialize the number of tries the player has made
count_number_of_tries = 1
# Obtain their initial guess
guess = int (input ("Please guess a number between 1 and 10: "))
while number_to_guess != guess:
print ("Sorry wrong number!")
# Check to see they have not exceeded the maximum number of attempts if so break out of loop
if count_number_of_tries == 3:
break
elif guess < number_to_guess:
print ("Your guess was lower than the number.")
else:
print ("Your guess was higher than the number.")
# Obtain their next guess and increment number of attempts
guess = int(input ("Please guess again: "))
count_number_of_tries += 1
# Check to see if they did guess the correct number
if number_to_guess == guess:
print ("Well done you won!")
print ("You took" + str(count_number_of_tries) + "attempts to complete the game.")
else:
print ("Sorry, you lose")
print ("The number you needed to guess was " + str(number_to_guess) + "." )
print ("Game Over.")
I dont know if the code should be at the bottom or in between somewhere.
I also want to remove the break if possible.
Great idea! In my mind, there are two ways of continuously asking the user to play until they enter something that will let you know they want to stop like 'q', 'quit', or 'exit'. First you could nest all of your current code a while loop (indent and write 'while(): before the code), or turn your current code into a function, and call it over and over again until the user enters the exit command
Ex:
lets say i can print hello world like this
# your game here
but now I want to keep printing it until the user enters 'quit'
user_input = '.' # this char does not matter as long as it's not 'quit'
while user_input != 'quit': # check if 'user_input' is not 'quit'
# your game here
user_input = input('Press any key to continue (and enter) or write "quit" to exit: ') # prompt user to enter any key, or write quit
Put all of that code in a game() function.
Underneath, write
while True:
game()
play=int(input('Play again? 1=Yes 0=No : '))
if play == 1:
pass
else:
break
print("Bye!")
I think this should do it, just a basic while loop
playAgain = 'y'
while playAgain == 'y':
print ("Welcome to the Number Guessing Game in Python!")
# Initialize the number to be guessed
number_to_guess = 7
# Initialize the number of tries the player has made
count_number_of_tries = 1
# Obtain their initial guess
guess = int (input ("Please guess a number between 1 and 10: "))
while number_to_guess != guess:
print ("Sorry wrong number!")
# Check to see they have not exceeded the maximum number of attempts if so break out of loop
if count_number_of_tries == 3:
print("You've guessed more than three times, you're pretty bad")
elif guess < number_to_guess:
print ("Your guess was lower than the number.")
else:
print ("Your guess was higher than the number.")
# Obtain their next guess and increment number of attempts
guess = int(input ("Please guess again: "))
count_number_of_tries += 1
# Check to see if they did guess the correct number
if number_to_guess == guess:
print ("Well done you won!")
print ("You took " + str(count_number_of_tries) + " attempts to complete the game.")
else:
print ("Sorry, you lose")
print ("The number you needed to guess was " + str(number_to_guess) + "." )
print ("Game Over.")
playAgain = (input ("Type y to play again, otherwise press enter: "))
print("Goodbye gamer")
You can add a while loop to the outermost layer that randomly generates the value of number_to_guess on each startup. And ask if you want to continue at the end of each session.
import random
print("Welcome to the Number Guessing Game in Python!")
number_range = [1, 10]
inp_msg = "Please guess a number between {} and {}: ".format(*number_range)
while True:
# Initialize the number to be guessed
number_to_guess = random.randint(*number_range)
# Initialize the number of tries the player has made
count_number_of_tries = 1
# Obtain their initial guess
guess = int(input(inp_msg))
while number_to_guess != guess:
print("Sorry wrong number!")
# Check to see they have not exceeded the maximum number of attempts if so break out of loop
if count_number_of_tries == 3:
break
elif guess < number_to_guess:
print("Your guess was lower than the number.")
else:
print("Your guess was higher than the number.")
# Obtain their next guess and increment number of attempts
guess = int(input("Please guess again: "))
count_number_of_tries += 1
# Check to see if they did guess the correct number
if number_to_guess == guess:
print("Well done you won!")
print("You took" + str(count_number_of_tries) + "attempts to complete the game.")
else:
print("Sorry, you lose")
print("The number you needed to guess was " + str(number_to_guess) + ".")
if input("Do you want another round? (y/n)").lower() != "y":
break
print("Game Over.")
Trying my hand at writing a very simple Game of Chance game on Codecademy while working through their Python course. I was doing ok (I think) for a while and the code returned what I expected it to, but now it feels I'm stuck and googling things frantically hasn't really helped me and I don't just want to look at the actual solution because where's the fun in that so here goes.
My thought process was the game should initially ask the player to input their guess and their bid, then run the code in game() and print the outcome. This was then to be locked in a while loop to check if the user wanted to continue playing or not and if the answer was "Yes" to restart the game() function again. This is where I am stuck as I just can't figure out what to put in line 26 after the "Yes" check returns True.
I guess the TL/DR version of my actual question is how do you (without giving the actual code away) call a function from within a while loop? Wondering if perhaps I'm simply headed in the wrong direction here and need to review while loops once more.
Thanks!
# Import stuff
import random
# Generate random number from 1 - 9
num = random.randint(1, 10)
# The actual game, asking user for input and returning the outcome
def game():
guess = int(input("Guess the number: "))
bid = int(input("Bet on the game: "))
money = 100
if guess == num:
money = (money + bid)
print("You Won")
print("You now have: " + str(money) +" money")
return money
else:
money = (money - bid)
print("You lost, you will die poor")
print("You now have: " + str(money) +" money")
return money
# Run game() while there's still money left in the pot
def structure():
while money > 0:
another_go = input("Would you like to play again? Yes or No: ")
if another_go == "Yes":
game() # This is where I'm stuck
elif another_go == "No":
print("Oh well, suit yourself")
break
else:
print("Pick Yes or No")
print(another_go)
game()
Ok so a few things to go through here.
First off, the concept of a local variable is coming into play here and is why your money variable is not communicating properly between your two functions. Each of your functions uses it's own money variable, which is completely independent of the other.
So this is the root of your current problem, where your money > 0 loop never actually runs. Secondly, although this might have just been done for troubleshooting, you don't actually call structure which is supposed to control game().
Lets try something like this where we keep money in the structure function and pass an update version to the game function as a parameter. Then, because you have game() returning money, you can just update the money value in your structure() call.
# Import stuff
import random
# Generate random number from 1 - 9
num = random.randint(1, 10)
# The actual game, asking user for input and returning the outcome
def game(money):
guess = int(input("Guess the number: "))
bid = int(input("Bet on the game: "))
if guess == num:
money = (money + bid)
print("You Won")
print("You now have: " + str(money) +" money")
return money
else:
money = (money - bid)
print("You lost, you will die poor")
print("You now have: " + str(money) +" money")
return money
# Run game() while there's still money left in the pot
def structure():
money = 100
money = game(money)
while money > 0:
another_go = input("Would you like to play again? Yes or No: ")
if another_go == "Yes":
money = game(money) # This is where I'm stuck
elif another_go == "No":
print("Oh well, suit yourself")
break
else:
print("Pick Yes or No")
print(another_go)
structure()
Notice because of how your while loop is written, in order to get game() to run the first time I had to call it before the while loop. Maybe as a challenge, see if you can be rewrite the structure of your loop so that you don't have to do this!
Welcome to SO. Your code is overall fine. Here's one way to slightly change your code to make it work:
... Most of the code ...
money = 10
def structure():
another_go = "Yes" # initialize to 'Yes', so we'll
# always have a first game.
while money > 0:
if another_go == "Yes":
game() # This is where I'm stuck
elif another_go == "No":
print("Oh well, suit yourself")
break
else:
print("Pick Yes or No")
print(another_go)
# move 'another go' to the end of the loop
another_go = input("Would you like to play again? Yes or No: ")
structure() # call this function to start
# make money a global parameter with a -ve value
money = -1
def game():
global money
guess = int(input("Guess the number: "))
bid = int(input("Bet on the game: "))
# Then, if money has default(game started for first time), update it
if(money < 0):
money = 100
.
.
.
.
while money > 0:
global money
another_go = input("Would you like to play again? Yes or No: ")
if another_go == "Yes":
game(money) # Pass remaining money to game()
.
.
.
So this is my random number guessing program I made. It asks the user to input two numbers as the bound, one high and one low, then the program will choose a number between those two. The user then has to try and guess the number chosen by the program. 1) How do I get it to ask the user if they would like to play again and upon inputting 'yes' the program starts over, and inputting 'no' the program ends? 2) How do I create an error trap that tells the user "Hey you didn't enter a number!" and ends the program?
def main(): # Main Module
print("Game Over.")
def introduction():
print("Let's play the 'COLD, COLD, HOT!' game.")
print("Here's how it works. You're going to choose two numbers: one small, one big. Once you do that, I'll choose a random number in between those two.")
print("The goal of this game is to guess the number I'm thinking of. If you guess right, then you're HOT ON THE MONEY. If you keep guessing wrong, than you're ICE COLD. Ready? Then let's play!")
small = int(input("Enter your smaller number: "))
large = int(input("Enter your bigger number: "))
print("\n")
return small, large
def game(answer):
c = int(input('Input the number of guesses you want: '))
counter = 1 # Set the value of the counter outside loop.
while counter <= c:
guess = int(input("Input your guess(number) and press the 'Enter' key: "))
if answer > guess:
print("Your guess is too small; you're ICE COLD!")
counter = counter + 1
elif answer < guess:
print("Your guess is too large; you're still ICE COLD!")
counter = counter + 1
elif answer == guess:
print("Your guess is just right; you're HOT ON THE MONEY!")
counter = c + 0.5
if (answer == guess) and (counter < c + 1):
print("You were burning hot this round!")
else:
print("Wow, you were frozen solid this time around.", "The number I \
was thinking of was: " , answer)
def Mystery_Number(a,b):
import random
Mystery_Number = random.randint(a,b) # Random integer from Python
return Mystery_Number # This function returns a random number
A,B = introduction()
number = Mystery_Number(A,B) # Calling Mystery_Number
game(number) # Number is the argument for the game function
main()
You'd first have to make game return something if they guess right:
def game(answer):
guess = int(input("Please put in your number, then press enter:\n"))
if answer > guess:
print("Too big")
return False
if answer < guess:
print("Too small")
return False
elif answer == guess:
print("Your guess is just right")
return True
Then, you'd update the 'main' function, so that it incorporates the new 'game' function:
def main():
c = int(input("How many guesses would you like?\n"))
for i in range(c):
answer = int(input("Your guess: "))
is_right = game(answer)
if is_right: break
if is_right: return True
else: return False
Then, you'd add a run_game function to run main more than once at a time:
def run_game():
introduction()
not_done = False
while not_done:
game()
again = input('If you would like to play again, please type any character')
not_done = bool(again)
Finally, for error catching, you'd do something like this:
try:
x = int(input())
except:
print('That was not a number')
import sys
sys.exit(0)
how do I make it restart when the user types "yes"
import random
answer=(random.randint (1,100))
play_again="yes"
tries=(0)``
guess=int(input("I'm thinking of a number between 1 and 100 "))
tries+=1
while play_again=="yes":
if (guess<answer):
guess=int(input("its higher than "+str(guess)+" "))
tries+=1
elif (guess>answer):
guess=int(input("it's lower than "+str(guess)+" "))
tries+=1
elif (guess==answer):
print("well done! You guessed the number in "+str(tries)+" guesses!")
play_again=input("would you like to play again?")
how do I make the game restart after the user wins when they type "yes"?
use two loops. one outer with play_again == "yes" and one inner with guess != answer.
while play_again == "yes":
# get input
while guess != answer:
# if lower:
# get guess
# if higher
# get guess
# get play_again
You can do this , create a function !
import random
import sys
def main():
# your code here
while True:
play_again = input("play again? :") # For python 2 raw_input()
if play_again == "yes":
main()
else:
sys.exit()
Something like this !
I hope this helps you!!
With a function that calls itself
def main():
# your code goes here
if input('Play again?') == 'yes':
main()