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
Related
A random number between 1 and 6, this represents a roll of a dice. The random number becomes the number of allowed guesses from the user. I cannot get the dice number to be same as amount of guesses allowed.
This is what I have so far:
import random
number = random.randint(1, 100)
player_name = input("Hello, What's your name?")
number_of_guesses = 0
print('okay! '+ player_name+ ' I am guessing a number between 1 and 100:')
min_value = 1
max_value = 6
print(random.randint(min_value, max_value))
while number_of_guesses < 5:
guess = int(input())
number_of_guesses += 1
if guess < number:
print("Your guess is too low")
if guess > number:
print("Your guess is too high")
if guess == number:
break
if guess == number:
print("You guessed the number in " + str(number_of_guesses) + " tries!")
else:
print("You did not guess the number, the number was " + str(number))
OK, this should fix your issues:
import random
number = random.randint(1, 100)
player_name = input("Hello, What's your name?")
number_of_guesses = 0
print('okay! '+ player_name+ ' I am guessing a number between 1 and 100:')
max_guesses = random.randint(1, 6)
print(f"You have {max_guesses} tries. ")
won = False
while number_of_guesses < max_guesses:
guess = int(input())
number_of_guesses += 1
if guess < number:
print("Your guess is too low")
if guess > number:
print("Your guess is too high")
if guess == number:
won = True
break
if won:
print("You guessed the number in " + str(number_of_guesses) + " tries!")
else:
print("You did not guess the number, the number was " + str(number))
However, this seems like some starting-out project, so it is important to understand what every code line is doing. In case you are not sure about anything, ask away :)
It looks like you're printing the random number, but not really using it. Could you try the following:
import random
number = random.randint(1, 100)
player_name = input("Hello, What's your name?")
number_of_guesses = 0
print('okay! '+ player_name+ ' I am guessing a number between 1 and 100:')
min_value = 1
max_value = 6
random_number = random.randint(min_value, max_value)
print(random_number)
while number_of_guesses < random_number:
guess = int(input())
if guess < number:
print("Your guess is too low")
if guess > number:
print("Your guess is too high")
if guess == number:
break
number_of_guesses += 1
if guess == number:
print("You guessed the number in " + str(number_of_guesses) + " tries!")
else:
print("You did not guess the number, the number was " + str(number))
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.
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
The code works fine, but I can't figure out how to completely restart the program. I put continue in the code and I know that is not correct, because I want it to restart completely after you guess the correct number and it displays 'Congratulations! You guessed my number in _ guesses.
import random
guesses = 0
number = random.randint(1, 100)
print('I am thinking of a number between 1 and 100.')
while guesses < 100:
guess = int(input('Guess? '))
guesses = guesses + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
continue
if guess == number:
guesses = str(guesses)
print('Congratulations! You guessed my number in ' + guesses + ' guesses!')
If you want to keep on guessing and start the game automatically, you need to do a recursive call:
import random
def guess_func():
number = random.randint(1, 100)
guesses = 0
while True:
guess = int(raw_input("Enter your guess: "))
if guess < number:
print('Your guess is too low.')
guesses += 1
if guess > number:
print('Your guess is too high.')
guesses += 1
if guess == number:
print "Congratulations! You guessed my number in [{}] guesses".format(guesses)
print "Let's keep on guessing!"
return guess_func()
guess_func()
so like this:
while True:
guesses = 0
while guesses < 100:
if guesses == 100:
break
...
if guess == number:
print ...
yorn = input "do you want to try again?")
if yorn == 'n':
break
so just wrap your code in an outer while, obviously i skipped a lot of your code
I have an issue with my simple guess the number game in python.The code is given below.The program never gives me a correct guess,it keep asking the number.
import random
import time
time1 = time.time()
number = random.randint(1,1000)
print ("welcome to the guessing game")
name = input("what is your name? ")
print("well, " + name + " iam thinking of the number between 1 and 1000")
while True:
guess = int(input("guess: ") )
if guess > number:
print("too high!")
if guess < number:
print("too low!")
if guess == number:
break
print("yahoo,you guessed the number!")
input()
time2 = time.time()
that is number guessing game in python 3.
You need to indent the code correctly, you should also use if/elif's as guess can only be one of higher, lower or equal at any one time. You also need to print before you break on a successful guess:
while True:
guess = int(input("guess: ") )
if guess > number:
print("too high!")
elif guess < number:
print("too low!")
elif guess == number:
print("yahoo,you guessed the number!")
time2 = time.time()
break
There is no way your loop can break as your if's are nested inside the outer if guess > number:, if the guess is > number then if guess < number: is evaluated but for obvious reasons that cannot possibly be True so you loop infinitely.
import random
import time
time1 = time.time()
number = random.randint(1,1000)
print ("welcome to the guessing game")
name = input("what is your name? ")
print("well, " + name + " i am thinking of the number between 1 and 1000")
while True:
guess = int(input("guess: ") )
if guess > number:
print("too high!")
if guess < number:
print("too low!")
if guess == number:
print("yahoo,you guessed the number!")
time2 = time.time()
break
without changing too much, here is a working code.
secret_number = 5
chance = 1
while chance <= 3:
your_guess = int(input("Your Guess:- "))
chance = chance + 1
if your_guess == secret_number:
print("You Won !!")
break
else:
print("You failed..TRY AGAIN..")
import random as rand
# create random number
r =rand.randint(0,20)
i=0
l1=[]
while(i<4):enter code here
number = int(input("guess the number : "))
if(number in l1):
print("this number is alraedy entered")
i=i
else:
l1.append(number)
if(number == r):
print(number)
break
if(number>r):
print(" number is less than your number ")
elif(number<r):
print("number is greater than your number")
i =i+1
print("number is")
print(r)