This question already has answers here:
Repeat Game - Python Rock, Paper, Scissors
(2 answers)
Closed 1 year ago.
number = int(input("please choose your number: "))
while number != number_to_guess:
if number > number_to_guess:
number = int(input("Your guess is wrong it was bigger then the generated number, try again: "))
continue
if number < number_to_guess :
number = int(input("Your guess was wrong it was smaller then the generated number, try again: "))
if number == number_to_guess:
print("Congrats you won")
restart = input("Do you want to play again? if yes type y, if not you can close the window \n")
while restart not in ["y"]:
restart = input("please type y or close the window \n")
i want it as the title suggest to restart after the user types y, and i want it to always start with number input"choose your..." but i have no idea of how to do that
You can write the code in a function, and then, if you want to restart, call that function again
def game():
number = int(input("please choose your number: "))
number_to_guess = 5
while number != number_to_guess:
if number > number_to_guess:
number = int(input("Your guess is wrong it was bigger then the generated number, try again: "))
continue
if number < number_to_guess :
number = int(input("Your guess was wrong it was smaller then the generated number, try again: "))
if number == number_to_guess:
print("Congrats you won")
restart = input("Do you want to play again? if yes type y, if not you can close the window \n")
if restart == "y": #restart the game
game()
while restart not in ["y"]:
restart = input("please type y or close the window \n")
# main code
game()
We can use functions or a while loop for this.
with functions,
def game():
#implement game here
number = input()
#other stuff
while True:
game()
restart = input()
if restart != 'y':
break # exit game
Note: this is pretty basic logic, refer to the tutorials here for more information on functions and loops.
Related
I'm having issues with this random number guessing game. There are 2 issues: The first issue has to do with the counting of how many tries you have left. it should give you 3 changes but after the 2nd one it goes into my replay_input section where I am asking the user if they want to play again.
import random
# guess the # game
guess = input("Enter in your numerical guess. ")
random_number = random.randint(0, 10)
print(random_number) # used to display the # drawn to check if code works
number_of_guess_left = 3
# this is the main loop where the user gets 3 chances to guess the correct number
while number_of_guess_left > 0:
if guess != random_number:
number_of_guess_left -= 1
print(f"The number {guess} was an incorrect guess. and you have {number_of_guess_left} guesses left ")
guess = input("Enter in your numerical guess. ")
elif number_of_guess_left == 0:
print("You lose! You have no more chances left.")
else:
print("You Win! ")
break
The second part has to do with the replay input, I can't seem to get it to loop back to the beginning to restart the game.
replay_input = input("Yes or No ").lower()
if replay_input == "yes":
guess = input("Enter in your numerical guess. ")
The break statement exits a while loop. The code in the loop executes once, hits break at the end, and moves on to execute the code after the loop.
You can have the player replay the game by wrapping it in a function which I've called play_game below. The while True loop at the end (which is outside of play_game) will loop until it encounters a break statement. The player plays a game once every loop. The looping stops when they enter anything other than "yes" at the replay prompt which will make it hit the break statement.
import random
def play_game():
# guess the # game
guess = input("Enter in your numerical guess. ")
random_number = random.randint(0, 10)
print(random_number) # used to display the # drawn to check if code works
number_of_guess_left = 3
# this is the main loop where the user gets 3 chances to guess the correct number
while number_of_guess_left > 0:
if guess != random_number:
number_of_guess_left -= 1
print(f"The number {guess} was an incorrect guess. and you have {number_of_guess_left} guesses left ")
guess = input("Enter in your numerical guess. ")
elif number_of_guess_left == 0:
print("You lose! You have no more chances left.")
else:
print("You Win! ")
while True:
play_game()
replay_input = input("Yes or No ").lower()
if replay_input != "yes":
break
Please focus on the basics first before posting the questions here. Try to debug with tools like https://thonny.org/. However, I updated your code, just check.
import random
# guess the # game
random_number = random.randint(0, 10)
print(random_number)
# don't forget to convert to int
guess = int(input("Enter in your numerical guess. "))
number_of_guess_left = 3
# this is the main loop where the user gets 3 chances to guess the correct number
while number_of_guess_left > 0:
number_of_guess_left -= 1
if guess == random_number:
print("You Win! ")
break
else:
if number_of_guess_left == 0:
print("You lose! You have no more chances left.")
break
else:
print(f"The number {guess} was an incorrect guess. and you have {number_of_guess_left} guesses left ")
guess = int(input("Enter in your numerical guess. "))
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. (btw, yes I realize this part is a copy of my other question. This is a different problem in the same program, so I started it the same way.)
Anyways, I am having an issue with the last part of the program not taking any values. It is supposed to take the input for keep_playing and continue going if it is equal to 'y'. The issue is that it isn't actually making the variable equal anything(at least I don't think so.) So, whatever value I put in, it just prints the same response every time. Here is the small part of the code which isn't working, though I feel like it is something wrong with the rest of the code:
def keep_playing(attempts,keep_playing):
keep_playing = 'y'
if keep_playing == 'y':
guess(attempts)
keep_playing = str(input("Another game (y to continue)? "))
else:
print()
print("Thanks for playing")
return keep_playing
The expected output is:
Enter a number between 1 and 100, or 0 to quit: 4
Too low, try again It's 66 for testing purposes
Enter a number between 1 and 100, or 0 to quit: 67
Too high, try again It's 66 for testing purposes
Enter a number between 1 and 100, or 0 to quit: 66
Congratulations! You guessed the right number!
There were 2 attempts
Another game (y to continue)? y
Enter a number between 1 and 100, or 0 to quit: 0
You quit too early
The number was 79
Another game (y to continue)? n
Thanks for playing!
But the actual output is:
Enter a number between 1 and 100, or 0 to quit: 4
Too low, try again It's 66 for testing purposes
Enter a number between 1 and 100, or 0 to quit: 67
Too high, try again It's 66 for testing purposes
Enter a number between 1 and 100, or 0 to quit: 66
Congratulations! You guessed the right number!
There were 2 attempts
Another game (y to continue)? y
Enter a number between 1 and 100, or 0 to quit: 0
You quit too early
The number was 79
Another game (y to continue)? n
Another game (y to continue)? y
>>>
Notice how no matter what I do, it continues to run. The first part with the higher and lower works fine, however the bottom part just seems to break, and I don't know how to fix it. If anyone has any solutions that would be greatly appreciated.
Also, in case anyone wanted to see the whole thing, in case there was in issue with that, here it is:
import random
def main():
global attempts
attempts = 0
guess(attempts)
keep_playing(attempts,keep_playing)
def guess(attempts):
number = random.randint(1,100)
print('')
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 It's",number, "for testing purposes") #printing the number makes it easier to fix :/
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
elif guess > number:
print("Too high, try again It's",number, "for testing purposes")
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()
keep_playing = str(input("Another game (y to continue)? "))
return keep_playing
else:
print()
print("You quit too early")
print("The number was ",number)
keep_playing = str(input("Another game (y to continue)? "))
return keep_playing
def keep_playing(attempts,keep_playing):
keep_playing = 'y'
if keep_playing == 'y':
guess(attempts)
keep_playing = str(input("Another game (y to continue)? "))
else:
print()
print("Thanks for playing")
return keep_playing
main()
I notice a couple things here
There is some issue with the naming of your function, python thinks that keep_playing is the str variable keep_playing and not the function. In my code below I will rename the function keep_playing to keep_playing_game.
You need to pass in the parameters when you call the function keep_playing_game so the function knows what the user input and attempts are.
Why are you setting keep_playing = 'y' in the first line of your function def keep_playing_game(attempts,keep_playing)? If you remove this line, your program should run as expected based on the value the user enters and not what the function assigns keep_playing to.
I would recommend trying something like this
import random
def main():
global attempts
attempts = 0
guess(attempts)
# keep_playing(attempts,keep_playing) -> this line should be removed
def guess(attempts):
number = random.randint(1,100)
print('')
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 It's",number, "for testing purposes") #printing the number makes it easier to fix :/
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
elif guess > number:
print("Too high, try again It's",number, "for testing purposes")
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()
keep_playing = str(input("Another game (y to continue)? "))
return keep_playing_game(keep_playing, attempts)
else:
print()
print("You quit too early")
print("The number was ",number)
keep_playing = str(input("Another game (y to continue)? "))
return keep_playing_game(keep_playing, attempts)
def keep_playing_game(keep_playing, attempts):
if keep_playing == 'y':
guess(attempts)
else:
print()
print("Thanks for playing")
return
return None
main()
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
import random
from random import randint
number = randint(1, 500)
guess = input("The computer has chosen a random number. Guess the number: ")
guess = int(guess)
while guess == number:
print("Congrats, you have won")
break
if guess > number:
print("Lower")
if guess < number:
print("Higher")
This code only allows the user to input one guess and then the program ends. Can someone help me fix this
You should think about your loop condition.
When do you want to repeat? This is the loop condition
When the guess is not correct. guess != number
What do you want to repeat? Put these inside the loop
Asking for a guess guess = int(input("Your guess: "))
Printing if it's higher or lower if guess > or < number: ...
What don't you want to repeat?
You need this before the loop
Deciding the correct number.
Setting the initial guess so the loop is entered once
You need this after the loop
Printing the "correct!" message, because you only exit the loop once the guess is correct
So we have:
number = random.randint(1, 100)
guess = 0
while guess != number:
guess = int(input("Your guess: "))
if guess > number:
print("Lower")
elif guess < number:
print("Higher")
print("Correct!")
Right now, your while loop is useless as once you are in it you break immediately. The rest of the code is not in a loop.
You should rather have an infinite loop with all your code, and break when there is a match:
from random import randint
number = randint(1, 500)
while True: # infinite loop
guess = input("The computer has chosen a random number. Guess the number: ")
guess = int(guess) # warning, this will raise an error if
# the user inputs something else that digits
if guess == number: # condition is met, we're done
print("Congrats, you have won")
break
elif guess > number: # test if number is lower
print("Lower")
else: # no need to test again, is is necessarily higher
print("Higher")
You must take input in the loop, because the value for each step has to be updated .
from random import randint
number = randint(1, 500)
while True:
guess = input("The computer has chosen a random number. Guess the number: ")
guess = int(guess)
if guess == number:
print("Congrats, you have won")
break
if guess > number:
print("Lower")
if guess < number:
print("Higher")
I need help changing the range and showing the user what the range is so they know if they are closer or not. I have given the description I have been given. On what I need to do . I have given the code that I have come up wit so far. Let me know if you need anything else from me.
Step 6 – Guiding the user with the range of values to select between
Add functionality so that when displaying the guess prompt it will display the current range
to guess between based on the user’s guesses accounting for values that are too high and too
low. It will start out by stating What is your guess between 1 and 100, inclusive?, but as
the user guesses the range will become smaller and smaller based on the value being higher
or lower than what the user guessed, e.g., What is your guess between 15 and 32,
inclusive? The example output below should help clarify.
EXAMPLE
----------------
What is your guess between 1 and 44 inclusive? 2
Your guess was too low. Guess again.
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
play()
#Part 1
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.")
print("\n")
def play():
''' Plays a guessing game'''
number = int(random.randrange(1,10))
guess = int(input("What is your guess between 1 and 10 inclusive ?: "))
number_of_guess = 0
while guess != number :
(number)
#Quit
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
#Guessing
if guess < number:
if guess < number:
guess = int(input("Your guess was too low. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
if guess > number:
if guess > number:
guess = int(input("Your guess was too high. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
#Winner
if guess == number :
number_of_guess += 1
print("Congratulations you won in " + str(number_of_guess) + " tries!")
again()
def again():
''' Prompts users if they want to go again'''
redo = input("Do you want to play again (Y or N)?: ")
if redo.upper() == "Y":
print("OK. Let’s play again.")
play()
elif redo.upper() == "N":
print("OK. Have a good day.")
sys.exit(0)
else:
print("I’m sorry, I do not understand that answer.")
again()
main()
What you'll need is a place to hold the user's lowest and highest guess. Then you'd use those for the range checks, instead of the hardcoded 1 and 11. With each guess, if it's a valid one, you then would compare it to the lowest and highest values, and if it's lower than the lowest then it sets the lowest value to the guess, and if it's higher than the highest it'll set the highest value to the guess. Lastly you'll need to update the input() string to display the lowest and highest guesses instead of a hardcoded '1' and '10'.
You need to simplify a lot your code. Like there is about 6 different places where you ask a new value, there sould be only one, also don't call method recursivly (call again() in again()) and such call between again>play>again.
Use an outer while loop to run games, and inside it an inner while loop for the game, and most important keep track of lower_bound and upper_bound
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
redo = "Y"
while redo.upper() == "Y":
print("Let’s play")
play()
redo = input("Do you want to play again (Y or N)?: ")
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.\n")
def play():
lower_bound, upper_bound = 0, 100
number = int(random.randrange(lower_bound, upper_bound))
print(number)
guess = -1
number_of_guess = 0
while guess != number:
guess = int(input(f"What is your guess between {lower_bound} and {upper_bound - 1} inclusive ?: "))
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
elif guess not in list(range(lower_bound, upper_bound)):
print("You're outside the range")
continue
number_of_guess += 1
if guess < number:
print("Your guess was too low")
lower_bound = guess
elif guess > number:
print("Your guess was too high")
upper_bound = guess
print("Congratulations you won in", number_of_guess, "tries!")
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I have an almost working code for my number guessing game. It runs completely fine up until the very end when asking the player if they want to play again and they type in "yes"--the Terminal outputs this:
Ha ha. You took too many guesses! I win! ^__^
Would you like to play again? (yes/no) yes
I'm thinking of a number between 1 and 99!
Ha ha. You took too many guesses! I win! ^__^
Would you like to play again? (yes/no)
I thought to just put the entire program in a while loop, but I have a few opening questions in the game that should only be asked the first time they run the program, and not every time they want to replay the game. (e.g Whats your name? Do you want to play?) I am not sure how to rerun the program but starting just after those initial questions. With my current code, I am lost at what to write for when the player types in "yes" at the ending to replay the game.
import random
import sys
guesses_taken = 0
number = random.randint(1, 99)
name = input("\nHello, what's your name? ")
print(f"\nNice to meet you, {name}.")
answer = input("Would you like to play a guessing game? (yes/no) ").lower()
while True:
if answer == "no":
print("\nToo bad, goodbye!\n")
sys.exit()
elif answer == "yes":
print(f"\nOkay, let's play!")
break
else:
print("\nSorry, I didn't get that.")
while True:
print("\nI'm thinking of a number between 1 and 99!")
while guesses_taken < 6:
guess = input("Take a guess: ")
guesses_taken += 1
if int(guess) > number:
print("\nYour guess is too high!\n")
elif int(guess) < number:
print("\nYour guess is too low!\n")
else:
print("\nArgh..you guessed my number! You win! -__-")
break
while guesses_taken >= 6:
print("\nHa ha. You took too many guesses! I win! ^__^")
break
again = input("\nWould you like to play again? (yes/no) ")
if again == "no":
break
sys.exit()
The variables guesses_taken & number will both retain their values when replaying, which makes for a not-very-interesting game. You need to do something to change that, like -
again = input("\nWould you like to play again? (yes/no) ")
if again == "no":
break
else:
guesses_taken = 0
number = random.randint(1, 99)
Functions, etc can make the code cleaner, but this is the minimal change you need to make to get things working.