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.
Related
I want my code to end after "thank you for playing", however underneath it, i get the message going back to "Guess my number:". I appreciate the help and advice! Thank you
def guess_number():
import random
import sys
guessesTaken = 0
max_number = float(input("What should the maxium number be for this game be? "))
print("")
number = random.randint(1,max_number)
while (guessesTaken) < 100000:
guesses = float(input("Guess my number: "))
guessesTaken = guessesTaken + 1
if guesses < number:
print("Your guess is too low.")
print("")
elif guesses > number:
print("Your guess is too high.")
print("")
elif guesses == number:
print("You guessed my number!")
print("")
again = (input("Do you wish to play again? (Y/N): "))
print("")
if again.lower() == "y":
guess_number()
else:
print("")
print("Thank you for playing!")
Instead of print("thank you for playing") try return "Thank you for playing!"
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.
I finally got it working! But for some reason the program prints out the previous error statement (too high or too low or please enter values between...), along with the value error message if the user enters in something that the try catches. Could anyone explain why? Any shortening/cleanup is also welcome. Sorry for any errors. Thanks!
'''
This is a guessing game that finds a random number, and then
Tells the user if their guess is too low or too high. It will also give
Error messages for any numbers outside of the accepted range, and will also
Give errors for anything not an integer.
At the end (if the user guesses correctly) it will ask if the
User would like to play again or quit.
'''
import random
def start_here():
print("Welcome to the guessing game!")
play_game()
def play_game():
random_number = random.randrange(1, 100)
correct = False
user_guess = True
while not correct:
try:
user_guess = int(input("Enter your guess: "))
except ValueError:
print("Please only use integers")
if user_guess > 100 or user_guess < 1:
print("Please only enter numbers between 1 and 100!")
elif user_guess > random_number:
print("Too high, try again. ")
elif user_guess < random_number:
print("Too low, try again! ")
elif user_guess == random_number:
break
if user_guess == random_number:
replay = (input("Great! You guessed it! would you like to play again? y or n"))
if replay == "y":
start_here()
else:
print("See ya later!")
start_here()
Keep in mind that the code after the try-except block gets executed irrespective of whether an exception was thrown or not. If the except block gets invoked you want your code to skip through the rest of the statements in the while loop and continue at the next iteration of the loop, where the user is prompted for input again. This can be achieved by using the continue keyword in the except block like so:
try:
user_guess = int(input("Enter your guess: "))
except ValueError:
print("Please only use integers")
continue
The continue statement directs the interpreter to skip the remaining statements in the current iteration of the loop. The flow of control can then re-enter the loop or exit, depending on the loop condition.
Now that your code runs the way it is intended to, here is how you can make it more concise:
Firstly, there is a neat feature in Python which allows you to write conditions like not 1 <= user_guess <= 100. These conditions are much quicker to read, and you can replace this in your code.
Secondly, the start_here() function is redundant. You can easily replace play_game() in its place with a few modifications like so:
import random
def play_game():
print("Welcome to the guessing game!") #Modification here
random_number = random.randrange(1, 100)
correct = False
user_guess = True
while not correct:
try:
user_guess = int(input("Enter your guess: "))
except ValueError:
print("Please only use integers")
continue #Modification here
if not 1<=user_guess<=100: #Modification here
print("Please only enter numbers between 1 and 100!")
elif user_guess > random_number:
print("Too high, try again. ")
elif user_guess < random_number:
print("Too low, try again! ")
elif user_guess == random_number:
break
if user_guess == random_number:
replay = (input("Great! You guessed it! would you like to play again? y or n"))
if replay == "y":
play_game() #Modification here
else:
print("See ya later!")
play_game() #Modification here
or you could entirely replace the play_game() function with a while loop like so:
import random
replay = 'y' #Modification here
while replay == 'y': #Modification here
print("Welcome to the guessing game!")
random_number = random.randrange(1, 100)
correct = False
user_guess = True
while not correct:
try:
user_guess = int(input("Enter your guess: "))
except ValueError:
print("Please only use integers")
continue
if not 1<=user_guess<=100 :
print("Please only enter numbers between 1 and 100!")
elif user_guess > random_number:
print("Too high, try again. ")
elif user_guess < random_number:
print("Too low, try again! ")
elif user_guess == random_number:
break
if user_guess == random_number: #Modification here
replay = input("Great! You guessed it! would you like to play again? y or n")
print("See ya later!") #Modification here
Here:
while not correct:
try:
user_guess = int(input("Enter your guess: "))
except ValueError:
print("Please only use integers")
if user_guess > 100 or user_guess < 1:
# etc
If the user input is not a valid int, you display an error message but still proceed with testing the value against the random number. You should instead skip the rest of the loop, or extract the part getting the user input into it's own loop. As a general rule, one function should do only one thing, then you use another function to control the whole program's flow:
def get_num():
while True:
try:
user_guess = int(input("Enter your guess: ").strip())
except ValueError:
print("Please only use integers")
continue
if user_guess > 100 or user_guess < 1:
print("Please only enter numbers between 1 and 100!")
continue
return user_guess
def again():
replay = input("would you like to play again? y or n"))
return replay.strip().lower() == "y"
def play_game():
random_number = random.randrange(1, 100)
while True:
user_guess = get_num()
if user_guess > random_number:
print("Too high, try again. ")
elif user_guess < random_number:
print("Too low, try again! ")
else:
# if it's neither too high nor too low then it's equal...
break
# no need to test again, we can only get here when the user
# found the number
print("Great! You guessed it!")
def main():
print("Welcome to the guessing game!")
while True:
play_game()
if not again():
break
if __name__ == "__main__":
main()
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>")