In my option 2 section of my code my loop isn't functioning properly and i can not figure out why. It keeps asking for an input again. I tried moving the input outside of the loop but that didn't work either.
import random
def display_menu():
print("Welcome to my Guess the Number Program!")
print("1. You guess the number")
print("2. You type a number for the computer to guess.")
print("3. Exit")
print()
def main():
display_menu()
option = int(input("Enter a menu option: "))
User pics a number randomly generated by the computer until user gets
the correct answer.
Outputs user guesses and number of attempts until guessed correct
if option == 1:
number = random.randint(1,10)
counter = 0
while True:
try:
guess = input("Guess a number between 1 and 10: ")
guess = int(guess)
print()
if guess < 1 or guess > 10:
raise ValueError()
counter += 1
if guess > number:
print("Too high.")
print()
elif guess < number:
print("Too low.")
print()
else:
print("You guessed it!")
print("You guessed the number in", counter, "attempts!")
break
except ValueError:
print(guess, "is not a valid guess")
print()
Option 2., User enters a number for the computer to guess.
Computer guesses a number within the range given.
Outputs computer guesses and number of guesses until computer gets
the correct number.
if option == 2:
print("Computer guess my number")
print()
while True:
try:
my_num = input("Enter a number between 1 and 10 for the computer to guess: ")
my_num = int(my_num)
counter = 0
counter += 1
print()
comp = random.randint(1,10)
if my_num < 1 or my_num > 10:
raise ValueError()
if comp > my_num:
print("Computer guessed", comp,"to High")
elif comp < my_num:
print("Computer guessed", comp,"to Low")
else:
print("Computer guessed the right number!" , comp)
print("Computer guessed the right number in", counter, "attempts!")
break
except ValueError:
print(my_num, "is not a valid entry")
print()
continue
"""
Ends game
"""
if option == 3:
print("Goodbye")
if __name__ == '__main__':
main()
You should ask for input before the loop. counter should be initialised before the loop too.
if option == 2:
print("Computer guess my number")
print()
# these three lines will be run once before the loop
my_num = input("Enter a number between 1 and 10 for the computer to guess: ")
my_num = int(my_num)
counter = 0
while True:
try:
comp = random.randint(1,10)
counter += 1
print()
if my_num < 1 or my_num > 10:
raise ValueError()
if comp > my_num:
print("Computer guessed", comp,"to High")
elif comp < my_num:
print("Computer guessed", comp,"to Low")
else:
print("Computer guessed the right number!" , comp)
print("Computer guessed the right number in", counter, "attempts!")
break
except ValueError:
print(my_num, "is not a valid entry")
print()
continue
As an aside, instead of randomly guessing, you can improve the computer's guessing by using binary search, where the number of tries has an upper bound.
Related
I have a program that works fine, however I need to make it so that it can execute again when the if statement regarding playing again is satisfied.
import random
n=random.randint(0,10)
print(n)
number= int(input('Guess what the number is'))
count=0
while number !=n:
count=count+1
number= int(input('Guess what the number is'))
if number< n:
print("that is too low")
elif number>n:
print("That is too high")
else:
print("You got it right in"+ " "+str(count+1)+" "+ "tries")
print(count+1)
yesorno= str(input('Do you want to play again? y or n'))
if yesorno=="y":
number= int(input('Guess what the number is'))
elif yesorno=="n":
print("Goodbye")
If you don't want an ugly big while loop, use functions. It makes your code cleaner.
import random
def play():
input("Guess a number between 1 and 10: ")
random_number = random.randint(1, 10)
guess = None
attempts = 0
while guess != random_number:
guess = int(input("Pick a number from 1 to 10: "))
attempts += 1
if guess < random_number:
print("TOO LOW!")
elif guess > random_number:
print("TOO HIGH!")
print("YOU GOT IT! The number was {}, you got it in {} attempts.".format(random_number, attempts))
def main():
play()
while input("Play again? (y/n) ").lower() != "n":
play()
main() # Call the main function
import random
n=random.randint(0,10)
count = 0
while True:
count=count+1
number= int(input('Guess what the number is'))
if number< n:
print("that is too low")
elif number>n:
print("That is too high")
else:
print("You got it right in"+ " "+str(count)+" "+ "tries")
print(count)
yesorno= str(input('Do you want to play again? y or n'))
if yesorno=="y":
n=random.randint(0,10)
count = 0
elif yesorno=="n":
print("Goodbye")
break
import random
n=random.randint(0,10)
print(n)
count=0
while True:
count=count+1
number= int(input('Guess what the number is '))
if number< n:
print("that is too low")
elif number>n:
print("That is too high")
elif number == n:
print("You got it right in"+ " "+str(count+1)+" "+ "tries")
print(count+1)
yesorno= str(input('Do you want to play again? y or n'))
if yesorno=="n":
print("Goodbye")
break
Use a while loop with a condition that will always be true, like while True:.
To stop this infinite loop, use the break statement within the while loop.
If user inputs "y", the loop will continue because it has not been told the break.
So, im new to python and i have this challenge: I have to make the Guess the Number game, between me and computer. So this is where im at so far.
import random
the_number = random.randint(1, 4)
guess = 0
print(the_number)
while guess != the_number:
guess = int(input("Please enter a number: "))
if guess > the_number:
print("Player guess lower...\n")
elif guess < the_number:
print("Player guess higher...\n")
else:
print("Game Over! The number was", the_number,"The Player wins!")
break
guess = random.randint(1, 100)
if guess > the_number:
print("Computer guess lower...\n")
elif guess < the_number:
print("Computer guess higher...\n")
else:
print("Game Over! The number was", the_number,"The Computer wins!")
break
print("Thank you for playing")
I wanna know how to make this to not stop until one of us is right?
# Import random library
import random
# Assign random value between 1-100
secret_number = random.randint(1, 100)
# get the user guess
guess = int(input("Guess the secret number between 1-100: "))
# Loop untill guess not equal to secret number
while guess != secret_number:
if guess < secret_number:
print("Sorry, your guess is too low.")
else:
print("Sorry, your guess is too high.")
# guess the number again
guess = int(input("Guess the secret number between 1-100: "))
# This statement will execute after coming out of while loop
print("You guessed the number!")
You can do something like this to make the computer smarter.
import random
the_number = random.randint(1, 4)
guess = 0
print(the_number)
minPossible = 0
maxPossible = 100
while guess != the_number:
guess = int(input("Please enter a number: "))
if guess > the_number:
print("Player, guess lower...\n")
if guess < maxPossible:
maxPossible = guess - 1
elif guess < the_number:
print("Player, guess higher...\n")
if guess > minPossible:
minPossible = guess + 1
else:
print("Game Over! The number was", the_number, "The Player wins!")
break
guess = random.randint(minPossible, maxPossible)
if guess > the_number:
print("Computer, guess lower...\n")
maxPossible = guess - 1
elif guess < the_number:
print("Computer, guess higher...\n")
minPossible = guess + 1
else:
print("Game Over! The number was", the_number,"The Computer wins!")
print("Thank you for playing")
Your problem is the break statement at the end of the while loop. The code is iterating through the loop one time, then the break is ending the loop.
To get the desired output, you just need to tweak the code a bit, the break in the if statement for the computer is out of the loop of else, so it will stop the execution no matter what.
To counter this condition, you can move the break inside the else block. By doing this, the program will only break if either CPU or you correctly guess the right number.
One more thing i wanted to point out is you are printing the selecting number in the program, if it is a guessing game, isn't it supposed to be in the back-end of the code. By entering the printed number, you can win the game in the first iteration.
And just to point out, your program is selecting the number from (1, 4) but the computer is set to guess the number from (1, 100).
Kindly tick the answer if it is correct.
The modified code is -
import random
the_number = random.randint(1, 4)
guess = 0
while guess != the_number:
guess = int(input("Please enter a number: "))
if guess > the_number:
print("Player guess lower...\n")
elif guess < the_number:
print("Player guess higher...\n")
else:
print("Game Over! The number was", the_number,"The Player wins!")
break
guess = random.randint(1, 4)
if guess > the_number:
print("Computer guess lower...\n")
elif guess < the_number:
print("Computer guess higher...\n")
else:
print("Game Over! The number was", the_number,"The Computer wins!")
break
print("Thank you for playing")
Running Python code for guessing game - if guess number outside of range - do not want it to count against tries. Code works but counts erroneous numbers as tries.
My code:
import random
print("The number is between 1 and 10")
print("You have 5 tries!")
theNumber = random.randrange(1,10)
maxTries = 5
tries = 1
guess = int(input("Take a guess: "))
while ((tries < maxTries) & (guess != theNumber)):
try:
if guess > theNumber:
print("Guess lower...")
elif guess < theNumber:
print("Guess higher...")
if guess > 10:
raise ValueError
except ValueError:
print("Please enter a numeric value between 1 and 10.")
#continue
guess = int(input("Guess again: "))
tries = tries + 1
if(guess == theNumber):
print("You guessed it! The number was", theNumber)
print("And it only took you", tries, "tries!\n")
else:
print("You failed to guess", theNumber, "!")
It allows continued guessing up to 5 tries as long as guess is between 1 and 10. If outside of this range - it will not count as a try but tells the user to "Please enter a numeric value between 1 and 10"). Which the code does - it just counts those tries when I do not want it to work that way.
Try this one:
import random
min_number = 1
max_number = 10
number = random.randrange(min_number, max_number + 1)
print(number) # To know the number you are guessing
maximum_tries = 5
print(f"The number is between {min_number} and {max_number}")
print(f"You have {maximum_tries} tries!")
guess = int(input("Take a guess: "))
j = 1
while True:
if guess > max_number or guess < min_number:
print("Please enter a numeric value between 1 and 10.")
j = j - 1
elif guess > number:
print("Guess lower...")
print("You failed to guess", j, "!")
elif guess < number:
print("Guess higher...")
print("You failed to guess", j, "!")
if guess == number:
print("You guessed it! The number was", number)
print("And it only took you", j, "tries!\n")
break
if j == maximum_tries:
break
guess = int(input("Guess again: "))
j = j + 1
I need to generate a random number from 1 to 9 and ask the user to guess it. I tell the user if its too high, low, or correct. I can't figure out how to keep the game going until they guess it correctly, and once they get it right they must type in exit to stop the game. I also need to print out how many guesses it took for them in the end. Here's my code so far:
import random
while True:
try:
userGuess = int(input("Guess a number between 1 and 9 (including 1 and 9):"))
randomNumber = random.randint(1,9)
print (randomNumber)
except:
print ("Sorry, that is an invalid answer.")
continue
else:
break
if int(userGuess) > randomNumber:
print ("Wrong, too high.")
elif int(userGuess) < randomNumber:
print ("Wrong, too low.")
elif int(userGuess) == randomNumber:
print ("You got it right!")
import random
x = random.randint(1,9)
print x
while (True):
answer=input("please give a number: ")
if ( answer != x):
print ("this is not the number: ")
else:
print ("You got it right!")
break
Here is the solution for your problem from:
Guessing Game One Solutions
import random
number = random.randint(1,9)
guess = 0
count = 0
while guess != number and guess != "exit":
guess = input("What's your guess?")
if guess == "exit":
break
guess = int(guess)
count += 1
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
else:
print("You got it!")
print("And it only took you",count,"tries!")
from random import randint
while 1:
print("\nRandom number between 1 and 9 created.")
randomNumber = randint(1,9)
while 1:
userGuess = input("Guess a number between 1 and 9 (including 1 and 9). \nDigit 'stop' if you want to close the program: ")
if userGuess == "stop":
quit()
else:
try:
userGuess = int(userGuess)
if userGuess > randomNumber:
print ("Wrong, too high.")
elif userGuess < randomNumber:
print ("Wrong, too low.")
else:
print ("You got it right!")
break
except:
print("Invalid selection! Insert another value.")
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I wanted to create a guessing game to get more comfortable programming, The user has up to 100 guesses(yes more than enough). If the number is too high or too low it have them type in a new input, if its correct it will print correct.Now I simply want to have it setup to where I ask them would they like to play again. I think I have an idea of to set it up, by separating them into two functions?
I am aware that is not currently a function but should put this as a fucntion and then put my question as an if statement in its own function?
import random
randNum = random.randrange(1,21)
numguesses = 0
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
Here's a simple way to do as you asked.I made a function and when you get the thing correct it asks if you want to play again and if you enter "yes" then it resets the vars and runs the loop again. If you enter anything but "yes" then it breaks the loop which ends the program.
import random
def main():
randNum = random.randrange(1,21)
numguesses = 0
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
x = input("would you like to play again?")
if x == "yes":
main()
else:
break
main()
Here is another way to do
import random
randNum = random.randrange(1,21)
numguesses = 0
maxGuess = 100
print("Guessing number Game - max attempts: " + str(maxGuess))
while True:
numguesses +=1
userguess = int(input("What is your guess [1 through 20]? "))
if userguess < randNum:
print("Too Low")
elif userguess > randNum:
print("Too High")
else:
print("Correct. You used ",numguesses," number of guesses")
break
if maxGuess==numguesses:
print("Maximum attempts reached. Correct answer: " + str(randNum))
break
import random
randNum = random.randrange(1, 21)
guess = 0
response = ['too low', 'invalid guess', 'too hight', 'correct']
def respond(guess):
do_break = None # is assigned True if user gets correct answer
if guess < randNum:
print(response[0])
elif guess > randNum:
print(response[2])
elif guess < 1:
print(response[1])
elif guess == randNum:
print(response[3])
do_continue = input('do you want to continue? yes or no')
if do_continue == 'yes':
# if player wants to play again start loop again
Guess()
else:
# if player does'nt want to play end game
do_break = True # tells program to break the loop
# same as ''if do_break == True''
if do_break:
#returns instructions for loop to end
return True
def Guess(guess=guess):
# while loops only have accesse to variables of direct parent
# which is why i directly assigned the guess variable to the Fucntion
while guess < 100:
guess -= 1
user_guess = int(input('What is your guess [1 through 20]?'))
# here the respond function is called then checked for a return
# statement (note i don't know wheter this is good practice or not)
if respond(user_guess):
# gets instructions from respond function to end loop then ends it
break
Guess()
Yet another way with two while loops
answer = 'yes'
while answer == 'yes':
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
break #Stop while loop if user guest, hop to the first loop with answer var
answer = raw_input("Would you like to continue? yes or no\n>")