I am trying to create a game that will ask the user to make a guess and if the guess is lower than the randomly generated integer, then it'll print ('Too low! Try again.), if the guess higher than the guess then it will print ('Too high! Try again) and if guess is equal to the random integer then it will ask the user if she wants to play again. This is where I am having trouble with - how can I have the code loop it back to recreate the random integer and start the loop if 'y' is entered?
import random
def main():
again='y'
count=0
while again=='y':
print('I have a number between 1 to 1000.')
print('Can you guess my number?')
print('Please type your first guess')
number=random.randint(1, 1000)
print(number)
guess=int(input(''))
while guess !='':
if guess>number:
print('Too high, try again!')
count+=1
print('count:',count)
guess=int(input(''))
elif guess<number:
print('Too low, try again!')
count+=1
print('count:',count)
guess=int(input(''))
elif guess==number:
print('Excellent!! You guessed the number!!!!')
print('Would you like to try again? (y or n)')
count+=1
print('count:',count)
again=str(input(''))
else:
print('You entered an invalid value')
main()
You can do this by just adding one line with your code, use break in the inner while loop, in this portion below, it will break the inner loop if user guessed the number accurately with getting new input of again, then if again = 'y' it will start the outer loop again and random will generate again, otherwise the game will end.
elif guess==number:
print('Excellent!! You guessed the number!!!!')
print('Would you like to try again? (y or n)')
count+=1
print('count:',count)
again=str(input(''))
break # added this `break`, it will break the inner loop
Since you are in two loops you have to break the deepest one. Here are two ways for your situation.
Eather update "guess" to: '':
elif guess==number:
print('Excellent!! You guessed the number!!!!')
print('Would you like to try again? (y or n)')
count+=1
print('count:',count)
again=str(input(''))
guess=''
Or add a break after the again input:
elif guess==number:
print('Excellent!! You guessed the number!!!!')
print('Would you like to try again? (y or n)')
count+=1
print('count:',count)
again=str(input(''))
break
Related
The following project requires: Your program should implement a simple guessing game with the following requirements:
Generate a random number between 1 and 50 and then have the user guess the number. The program should tell the user whether they have guessed too high or too low and allow them to continue to guess until they guess the number or enter a 0 to quit.
When they guess the number it should tell them how many guesses it took. At the end, the program should ask them if they want to play again.
For example:
Enter a guess 1-50, or 0 to quit: 25
Too high!
Enter a guess 1-50, or 0 to quit: 15
Too low!
Enter a guess 1-50, or 0 to quit: 100
Guess must be between 1 and 50!
Enter a guess 1-50, or 0 to quit: 18
That's it! You took 3 guesses to get the number.
Would you like to play again? (Y/N)
I currently have everything settled except for two issues. I cannot seem to get the play again feature to work and for some reason the first number that is guessed will not say whether it is too low or too high.
My following code:
import random
play = True
randomNum = 45 #random.randrange(1,50)
guesses = 1
num = int(input())
print("Enter a guess 1-50, or 0 to quit:", num)
if num > 50 or num < 1:
print('Guess must be between 1 and 50!')
if num == randomNum:
print("That's it! You took", guesses, "guess to get the number.")
#print("Guess must be between 1 and 50!")
while num != randomNum:
guesses += 1
num = int(input())
print("Enter a guess 1-50, or 0 to quit:", num)
if num == 0:
break
elif num > 50 or num < 1:
print('Guess must be between 1 and 50!')
elif num > randomNum:
print("Too high!")
elif num < randomNum:
print("Too low!")
if num == randomNum:
print("That's it! You took", guesses, "guesses to get the number.")
print("Would you like to play again? (Y/N)")
letter = str(input())
if letter != 'Y':
play = False
I explained above what I have tried. I do believe that the issue is that the first guess does not enter the while loop. Unsure of how to fix this though.
First issue is that your while cycle only lasts until a number is guessed. So that means after you guess the first random number, your program will finish.
In order to avoid that you should declare your $play = True$ boolean on top of the cycle so you can declare your while cycle something like this:
play = True
while play:
# game goes here.
print("Would you like to play again? (Y/N)")
letter = str(input())
if letter != 'Y':
play = False
Then your cycle should continue while letter is Y or play remains True.
Second issue is that you ask for the number outside the cycle. That is not necessary, you can ask it inside after you construct your code like the example above.
I hope this clears things up.
ps. This is my first answer, so please point out if I did something wrong!
i am preparing a function to user to guess a random number generated by computer.
The output should be the number of guesses, and if the guess is correct, lower or higher than the generated number.
In the end the, the user should be asked if he wants to play again or not.
Everything is working excepts this last part, because i can't break the loop to stop the game.
Here's my code:
#random number guessing game
import random
def generate_random (min,max):
return random.randint (min,max)
#generate_random (1,100)
star_range=1
end_range=100
#targetnumber=generate_random(start_range,end_range)
#print (targetnumber)
def main():
targetnumber=generate_random(star_range,end_range)
number_of_guesses =0 #guarda o numero de tentativas do jogador
print ("Guess a number between 0 e 100.\n")
while True:
number_of_guesses +=1
guess = int(input("Guess #" + str(number_of_guesses) + ": "))
if guess > targetnumber:
print("\t Too High, try again.")
elif guess < targetnumber:
print ("\t Too low, try aain")
else:
print ("\t Correct")
print ("\t Congratulations. you got it in",number_of_guesses,"guesses.")
break
playagain=input("\n whould you like to play again? (y/n): ").lower()
while playagain != "y" or playagain != "n":
print ("Please print y to continue or n to exit")
playagain=input("\n whould you like to play again? (y/n): ").lower()
if playagain == "y":
continue
else:
break
My final output is always this one:
whould you like to play again? (y/n): n
Please print y to continue or n to exit
whould you like to play again? (y/n):
Can you please help me, letting me know what i am doing wrong?
Thank you very much
The condition evaluation is always True, hence you get into the loop again.
while playagain not in ['y', 'n']:
...
would satisfy your input check
Also, your continue/break condition is only evaluated if the while loop condition is met (i.e., the input was not correct)
It looks like you are continuing the second "while" loop and not moving back to your "game" code when you check the equality of the string "y" as the input, thus the question gets asked again. Instead, you should try refactoring the loops so that your game loop is nested inside the retry loop.
I need to show "Determinate loop" and "Indeterminate Loops" on this code. (nested)
This is a simple code, pick a random number, and gives you 2 opportunities to guess the number, if you can't, it will let you know what the magic number was and start the game again.
questions:
is there any other way to make the game start over? like a while or nested loop.
can I get an opinion if it is enough?
the problem with the code is, every time you make a guess, it prints
"Can you guess the magic number?"
how can it print that only at the beginning of the code and then only prints:
"try a lower number"
"try a higher number"
I feel like the code is not nested enough, anyway I can make it more professional?
repeat_the_game = True
def start():
import random
magic_number = random.randint(1, 10)
trying = 0
limit = 2
while trying < limit:
guess = int(input("can you guess the magic number?"))
trying += 1
if guess > magic_number:
print("try a lower number")
elif guess < magic_number:
print("try a higher number")
elif guess == magic_number:
print("wow, you are right")
break
else:
print("sorry, the magic number was", magic_number)
while repeat_the_game:
start()
Move the text out of the loop to a print statement. Then you can still keep fetching the input inside the loop:
repeat_the_game = True
def start():
import random
magic_number = random.randint(1, 10)
trying = 0
limit = 2
print("can you guess the magic number?")
while trying < limit:
trying += 1
guess = int(input())
if guess > magic_number:
print("try a lower number")
elif guess < magic_number:
print("try a higher number")
elif guess == magic_number:
print("wow, you are right")
break
else:
print("sorry, the magic number was", magic_number)
while repeat_the_game:
start()
However, if the second guess is still wrong you probably don't want to print "try a lower/higher number". If you guess it right the second time you do want to print "wow, you're right". I'd put the "try a lower/higher number" after an additional check of whether all tries have been used up already. You can move the "wow, you're right" part before that check:
while trying < limit:
guess = int(input())
trying += 1
if guess == magic_number:
print("wow, you are right")
break
if trying == limit:
continue
if guess > magic_number:
print("try a lower number")
elif guess < magic_number:
print("try a higher number")
else:
print("sorry, the magic number was", magic_number)
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I want to store a list of guesses the user has already made, so that when the user makes the next guess I can check that guess against a list of previous guesses. If the guess the user just made is in that list I want to tell the user to guess again and not count it as a attempt(5 attempts at guessing correct number)
tried using the append method to append the guesses to a blank list but I'm getting a "int obj has no append method" error.
import random
def guess_a_number():
chances = 5
random_number_generation = random.randint(1,21)
while chances != 0:
choice = int(input("Guess a number between 1-20, you only have {} chances left ".format(chances)))
if choice > random_number_generation:
print("Your number is too high, guess lower")
elif choice < random_number_generation:
print("Your number is too low, guess higher")
else:
print("You guessed the correct number!!!")
break
chances -= 1
if chances == 0:
try_again = input("Do you want to try play again? ")
if try_again.lower() == "yes":
guess_a_number()
else:
print("Better luck next time")
guess_a_number()
Try keeping a list of previous guesses and then check if guess in previous_guesses: immediately after the choice. You can use continue to skip the rest and prompt them again.
Just use a set or a list to hold the previously attempted numbers and check for those in the loop.
I think you already tried something similar but by the sound of it you were attempting to append to an int.
import random
while True:
chances = 5
randnum = random.randint(1, 21)
prev_guesses = set()
print("Guess a number between 1-20, you have {} chances ".format(chances))
while True:
try:
choice = int(input("what is your guess? "))
except ValueError:
print('enter a valid integer')
continue
if choice in prev_guesses:
print('you already tried {}'.format(choice))
continue
if choice > randnum:
print("Your number is too high, guess lower")
elif choice < randnum:
print("Your number is too low, guess higher")
else:
print("You guessed the correct number!!!")
break
chances -= 1
prev_guesses.add(choice)
print("you have {} chances left".format(chances))
if chances == 0:
print("You ran out of guesses, it was {}".format(randnum))
break
try_again = input("Do you want to play again? ")
if try_again.lower() not in ("y", "yes"):
print("Better luck next time")
break
Here is the concept of my game, the computer randomly generates a number from 1-100 and the player has to guess that number. If the number they guess is higher or lower the computer tells them so.
I added some code to make sure that the guess that the user enters is a number, but for some reason, it only works for their first guess.
import random
x = random.randint(1, 100)
guess = input("Guess the number")
while guess.isnumeric() == True:
if x > int(guess):
print("Too low, guess again")
guess = input("Guess the number")
if x < int(guess):
print("Too high, guess again")
guess = input("Guess the number")
if x == int(guess):
print ("That is correct!")
break
if guess.isnumeric() == False:
print("Please enter a valid number")
guess = input("Guess the number")
I don't really know how to else to explain it. But for example, if I guess the number 20 as my first guess, it would output too high or too low depending on the randomly generated number, but after that, if I input a bunch of random letters it would give me an error that the guess could not be compared to the randomly generated number.
I've fixed your code for you. Try this:
import random
x = random.randint(1, 100)
while True:
try:
guess = int(raw_input("Guess the number: "))
except ValueError:
print("Not a valid number, try again!")
continue
if guess < x:
print("Too low, guess again")
elif guess > x:
print("Too high, guess again")
elif x == guess:
print ("That is correct!")
break
You don't need to prompt the user for input after every guess, that's what the first input prompt is for. Because we are specifying while True, the user will get prompted to input a number every single time unless they enter the correct number, which in that case, we break the infinite loop.
Additionally, we can put the input statement in a try block, because we are casting the input as an integer right there. If the user enters a string, the program would otherwise fail if it tried to cast it as an integer, but if we except ValueError: and then continue, we will alert the user that their input is invalid, and then prompt them for input once again.
Your if statements are all independent:
if x > int(guess):
print("Too low, guess again")
guess = input("Guess the number")
if x < int(guess):
print("Too high, guess again")
guess = input("Guess the number")
if x == int(guess):
print ("That is correct!")
break
The second and third if statements will always test guess again, even if the first if test matched. And if the first if test matched and you entered a non-numeric guess value, those two tests will fail as the int() call will throw a ValueError exception.
You could tell Python that the tests are interdependent by using elif and else; now Python will only execute the first matching block, and skip the others entirely:
if x > int(guess):
print("Too low, guess again")
guess = input("Guess the number")
elif x < int(guess):
print("Too high, guess again")
guess = input("Guess the number")
else:
print ("That is correct!")
break
This means that execution continuous after the else block when either the if or elif tests matched.
Note that I used else at the end; if the number is neither too high nor too low, the number must be equal, there is no other option. There is no need to test for that explicitly.
You are now repeating yourself however. You are asking for a guess in 3 different places. You could ask once and let the loop take care of asking for a new value:
while True:
while True:
guess = input("Guess the number:")
if guess.isnumeric():
break
print("Not a valid number, try again!")
guess = int(guess)
if x > guess:
print("Too low, guess again")
elif x < guess:
print("Too high, guess again")
else:
print ("That is correct!")
break
That's a lot less repetition already; a separate while loop asks for a number until it is actually numeric, and guess is converted to int() just once.
You could remove that nested while True: and just use the outer one here, the result would be the same, provided you use the continue keyword to skip the rest of the loop when you don't have a numeric value:
while True:
guess = input("Guess the number:")
if not guess.isnumeric():
print("Not a valid number, try again!")
continue # skip to the top of the loop again, so ask again
guess = int(guess)
if x > guess:
print("Too low, guess again")
elif x < guess:
print("Too high, guess again")
else:
print ("That is correct!")
break
You need to surround your guessing logic in another loop that continues until the guess is correct.
pseudocode:
choose_target_answer
while player_has_not_guessed_answer
get_player_guess
if player_guess_is_valid
respond_to_player_guess
else
give_error_message