So i'm working on a guessing number game and one of the requirements is for the "range" of numbers to be updated so that the user with have an easier time with their guess'. I created a new input for when the number is either too high or too low. However, i'm not very good with loops and I can't figure out why my loop is repeating only once without my pasting the code over and over again. Can anyone help so the elif statements will repeat until the number is correct?
This is my code thus far...
import random
random_number = random.randint(1,100)
tries = 0
while tries < 800:
guess = input("Guess a random number between 1 and 100.")
tries += 1
try:
guess_num = int(guess)
except:
print("That's not a whole number!")
break
if not guess_num > 0 or not guess_num < 101:
print("That number is not between 1 and 100.")
break
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
break
elif guess_num > random_number:
print("Sorry that number is too high.")
guess_high = input("Guess a number between 0 and {} .".format(guess_num))
elif guess_num < random_number:
print("Sorry that number is too low.")
guess_low = input("Guess a number between {} and 100 .".format(guess_num))
else:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
import random
random_number = random.randint(1,100)
tries = 0
guess = input("Guess a random number between 1 and 100.")
while tries < 800:
tries += 1
try:
guess_num = int(guess)
except:
print("That's not a whole number!")
break
if not guess_num > 0 or not guess_num < 101:
print("That number is not between 1 and 100.")
break
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
break
elif guess_num > random_number:
print("Sorry that number is too high.")
guess = input("Guess a number between 0 and {} .".format(guess_num))
elif guess_num < random_number:
print("Sorry that number is too low.")
guess = input("Guess a number between {} and 100 .".format(guess_num))
else:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
Do not use break, as they terminate the while loop. See python language reference.
You should ask only once for guess_num. Remove the two input when the guess is too high or too low (BTW variable name guess was incorrect).
The last condition (out of tries) should be outside the while loop, since it will be executed when the number of tries is over 800.
Hint. A user can play this game with the equivlent of a binary search (start with 50, then guess 25 or 75 depending if higher/lower, etc). You should allow about 8 tries (not 800).
Here is how to update the ranges:
import random
random_number = random.randint(1,100)
tries = 0
low = 0
high = 100
while tries < 800:
if(tries == 0):
guess = input("Guess a random number between {} and {}.".format(low, high))
tries += 1
try:
guess_num = int(guess)
except:
print("That's not a whole number!")
break
if guess_num < low or guess_num > high:
print("That number is not between {} and {}.".format(low, high))
break
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
break
elif guess_num > random_number:
print("Sorry that number is too high.")
high = guess_num
guess = input("Guess a number between {} and {} .".format(low, high))
elif guess_num < random_number:
print("Sorry that number is too low.")
low = guess_num
guess = input("Guess a number between {} and {} .".format(low, high))
else:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
For which case does your loop only repeats once?
The loop would break (since you have a break statement in line 15 under the "if not guess_num > 0 or not guess_num < 101:") if the input guess is less than 0 or greater than 100.
If the user input an incorrect guess between 1 and 100, then the code does loop and hence the user is asked to input another number.
Although it does loop, the loop is not updating the range.
What you can do is set range_min and range_max as variables and change these variables according to if the guess is too low or too high.
See the following code:
import random
random_number = random.randint(1,100)
tries = 0
range_min = 0
range_max = 100
while tries < 800:
guess = input("Guess a random number between " + str(range_min +1) + " and " + str(range_max))
tries += 1
try:
guess_num = int(guess)
except:
print("That's not a whole number!")
break
if not guess_num > range_min or not guess_num < (range_max+1):
print("That number is not between str(range_min +1) + " and " + str(range_max)")
break
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
break
elif guess_num > random_number:
print("Sorry that number is too high.")
guess_high = input("Guess a number between 0 and {} .".format(guess_num))
range_max = guess_num
elif guess_num < random_number:
print("Sorry that number is too low.")
guess_low = input("Guess a number between {} and 100 .".format(guess_num))
range_min = guess_num
else:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
Here is how I would do it. Not sure if it works but the approach would be:
import random
random_number = random.randint(1,100)
max_tries = 100
tries = 0
left = 0
right = 100
found = False
def get_number():
try:
guess = int(input("Guss a random number between {} and {}".format(left, right)))
if guess > right or guess < left:
print("That number is not between {} and {}".format(left, right))
return guess
except:
print("That's not a whole number!")
get_number()
def update_range(guess):
if guess >= left:
left = guess
else:
right = guess
while tries <= max_tries and not found:
guess = get_number()
tries=+1
if guess == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
found = True
else:
update_range(guess)
if not found:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
As you can see I am using helper functions in order to reduce the number of if/else structures.
Also updating the range is necessary. And thanks to parametrized strings I can tell the user what's the range.
I also set a flag to know whether the user found the number or not at the end of the game
Related
The aim of this code is to get the computer to generate a random number and let the user try and guess what that number is in however many tries they choose. However, when they fail to guess correctly the program is supposed to print "You have failed in (x) tries" just once. Unfortunately this line keeps looping over and over again. Where have I gone wrong?
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
while guess != random_number:
if tries < limit:
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
else:
print(f"You have failed in {limit} tries")
tries = tries + 1
print (f"You have guessed {random_number} correctly")
guess(10)
It was looping forever because the incrementation of tries was done in the else block and there is no break keyword in else block too.
So, move tries = tries+1 in the if tries <limit: block and put break inside the else block as shown below:
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
while guess != random_number:
if tries < limit:
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
tries = tries + 1 # <--- move here
else:
print(f"You have failed in {limit} tries")
break; # <--- put break
print (f"You have guessed {random_number} correctly")
guess(10)
You need to keep a check of the tries.
You need to print the statement only in the user input is correct:
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
while tries<limit:
if tries < limit:
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
else:
print (f"You have guessed {random_number} correctly")
break
else:
print(f"You have failed in {limit} tries")
tries = tries + 1
guess(10)
You can use a for loop:
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
found=False
for i in range(limit):
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
else:
found=True
break
if found:
print (f"You have guessed {random_number} correctly")
else:
print(f"You have failed in {limit} tries")
guess(10)
There are multiple logical errors in your code,
the condition you are using in the while loop, guess != random_number, is to check if a number has been guessed correctly or not, not to check if the total number of guesses are exhausted.
No matter what happens, when the code will exit the while loop it will show the user that he/she has guessed correctly
Changing your code to take this into consideration will fix your problem. Below is a possible solution:
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
# Flag to check if the user is guessing the right or wrong value
# Default assumption is that user is guessing incorrectly
UserGuess = False
while tries < limit:
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
else:
# Changing flag and stopping the loop if the user guesses correctly
UserGuess = True
break
tries = tries + 1
if UserGuess:
print (f"You have guessed {random_number} correctly")
else:
print (f"You have failed in {limit} tries")
guess(10)
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>")