So I have to make a "game" on python were I think of a number and it tries to guess the number. I have to tell it if it's higher or lower than the number it guessed and continue from there. So far I have it doing what I need but I have no idea how to make python remember what numbers it's guessed. So If I tell it to guess a number between 1 and 10 and it guesses 7, I say it's too high it then guesses 4 and I say it's too low it might then guess and 8. Well I can't have it guess a number higher than 7 since I said it's lower than that already. Is there any way to make it remember that?
Here's my code:
from random import randrange
def lowHigh():
l = input ("Please input the low number range.")
numl = eval(l)
h = input ("Please input the high number range.")
numh = eval(h)
guess = randrange(1,numh + 1)
print (guess)
while True:
ask = input("Is this number correct? y for yes or n for no.")
if ask == 'y':
print("Yay! I guessed right!")
break
else:
lowOrHigh = input ("Is this number too high or low? h for high, l for low.")
if lowOrHigh == 'h':
guess = randrange(numl,guess-1)
print(guess)
else:
guess = randrange(guess+1,numh)
print(guess)
You can use two different numbers to indicate the lowest and highest guesses.
When the computer guesses a number and its higher actual number, you can make the highest = that number.
Same way when the computer guesses a number and its lower than actual number, you can make the lower = that number.
And each time you take random number between these two lowest and highest number only.
The code would look like -
from random import randrange
def lowHigh():
l = input ("Please input the low number range.")
numl = eval(l)
h = input ("Please input the high number range.")
numh = eval(h)
lowest = l
highest = h
while True:
guess = randrange(lowest,highest+1)
print (guess)
ask = input("Is this number correct? y for yes or n for no.")
if ask == 'y':
print("Yay! I guessed right!")
break
else:
lowOrHigh = input ("Is this number too high or low? h for high, l for low.")
if lowOrHigh == 'h':
highest = guess - 1
else:
lowest = guess
You can save the numbers it guessed in a list and then you check if a new guess is already in the list or not.
initialise an empty list like so:
guessed=[]
and then you can append guesses made by your program into the list
guessed.append(guess)
Demo:
from random import randrange
import time
def guessNumber(min_no, max_no):
""" Select number from the range. """
try:
return randrange(min_no, max_no)
except ValueError:
return min_no
def userNoInput(msg):
""" Get Number into from the user. """
while 1:
try:
return int(raw_input(msg))
except ValueError:
print "Enter Only Number string."
continue
def findMe():
"""
1. Get Lower and Upeer Value number from the User.
2. time sleep to guess number for user in between range.
3. While infinite loop.
4. Get guess number from the Computer.
5. User can check guess number and tell computer that guess number if correct ror not.
6. If Correct then print msg and break While loop.
7. If not Correct then
Ask Computer will User that guess number is Greate or Lower then Actual number.
7.1. If Greater then Set Max limit as guess number.
7.2. If Not Greater then Set Min limit as guess number.
7.3. Continue While loop
"""
min_no = userNoInput("Please input the low number range:")
max_no = userNoInput("Please input the high number range:")
print "Guess any number between %d and %d."%(min_no, max_no)
max_no += 1
time.sleep(2)
while True:
guess = guessNumber(min_no, max_no)
print "Computer guess Number:-", guess
ask = raw_input("Is this number correct? y for Yes or n for No:")
if ask.lower() == 'y':
print("Yay! I guessed right!")
break
else:
lowOrHigh = raw_input("Is this number too high or low? h for high, l for low.")
if lowOrHigh.lower() == 'h':
#- As guess number is higher then set max number to guess number.
max_no = guess
else:
#- As guess number is lower then set min number to guess number.
min_no = guess
findMe()
Output:
Please input the low number range:10
Please input the high number range:20
Guess any number between 10 and 20.
Computer guess Number:- 14
Is this number correct? y for Yes or n for No:n
Is this number too high or low? h for high, l for low.l
Computer guess Number:- 19
Is this number correct? y for Yes or n for No:n
Is this number too high or low? h for high, l for low.h
Computer guess Number:- 17
Is this number correct? y for Yes or n for No:n
Is this number too high or low? h for high, l for low.h
Computer guess Number:- 16
Is this number correct? y for Yes or n for No:n
Is this number too high or low? h for high, l for low.h
Computer guess Number:- 15
Is this number correct? y for Yes or n for No:y
Yay! I guessed right!
Note:
Python 2.7 : raw_input() method, print is statement.
Python 3.X : input() method, print is function.
Its very similar to a Binary Search Algorithm
Its just that the usual mid value in such algorithms can be replaced by randrange(Low,High)
I'm not sure if this is a working code but I suggest you do it recursively:
items= range(l,h)
def random_search(ask, items, l, h):
"""
Random search function.
Assumes 'items' is a sorted list.
The search range is [low, high)
"""
ask = input("Is this number correct? y for yes or n for no.")
lowOrHigh = input ("Is this number too high or low? h for high, l for low.")
elem = randrange(l,h)
if ask == 'y':
return elem
elif h == l:
return False
elif lowOrHigh == 'h':
items= range(l,elem)
return random_search(ask, items, l, elem)
else:
items= range(elem, h)
return random_search(ask, items, elem, h)
Related
I have a class project, where I am making a number guessing game. I have the following requirements:
#1. A main() function that holds the primary algorithm, but itself only passes information among other functions. main() must have the caller for random_int()
#2. A function called in main() (not nested in main()!) that compares the user's guess to the number from random_int() and lets the user know if it was too high or too low.
#3. A function called in main() that asks the user for a new guess.
#4. A function that prints out a string letting the user know that they won.
#5. Tell the user how many guesses it took them to get the correct answer.
I am currently having an issue trying to take the user inputted value "guess" and compare it with the value of a randomly generated integer "random_int" in a while loop in the function def high_low():
def random_int(size): #Generates a random integer from given parameters (size)
return randrange(1, size+1)
def new_guess(): #Prompts the user to enter an integer as their guess
guess = (input("Enter your guess (between 1 - 1000): "))
return guess
def high_low(random_int, new_guess): #Lets the user know if the number they guessed is too high or too low
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
I either get the error "guess not defined" or '>' not supported between instances of 'function' and 'function'
Here is all of the code for context, note though that most of it below what I have posted above is pseudocode for the purposes of figuring out the logic of the game's function, and I have not yet gone through with debugging.
#Python number guessing game
#Import randrange module
from random import randrange
#Initialize variables
attempts = 0
def random_int(size): #Generates a random integer from given parameters (size)
return randrange(1, size+1)
def new_guess(): #Prompts the user to enter an integer as their guess
guess = (input("Enter your guess (between 1 - 1000): "))
return guess
def high_low(random_int, new_guess): #Lets the user know if the number they guessed is too high or too low
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
new_guess()
def win(random_int, new_guess): #Prints that the answer is correct, along with the number of guesses it took
while guess == random_int:
if attempts >= 2: #If it took the user more than 1 attempt, uses "guesses" for proper grammar
print("You guessed the correct number, you win! It took you ", str(attempts()), " guesses.")
input("Would you like to play again? (Y/N): ")
if input == Y: #If user inputs "Y", runs the program again
main()
elif input == N: #If user inputs "N", terminates the program
break
elif attempts < 2: #If it took the user only 1 attempt, uses "guess" for proper grammar
print("You guessed the correct number, you win! It took you ", str(attempts()), " guess.")
input("Would you like to play again? (Y/N): ")
if input == Y: #If user inputs "Y", runs the program again
main()
elif input == N: #If user inputs "N", terminates the program
break
def main(): #Function to call all functions in the program
random_int(1000)
new_guess()
high_low(random, new_guess)
win()
main() #Calls the "main" function, runs the program
The code has a couple of issues I'll walk through all of them with an explanation so that we understand the reason why they happen at all. First we'll address all errors one by one.
Error-1
The first error on executing the code is '>' not supported between instances of 'function' and 'function'.
To understand that, notice the difference between Call-1 and Call-2 in below example code:
def f1():
return 1
def f2():
return 2
def less_than(n1, n2):
return n1 < n2
less_than(f1, f2) # Call-1: this will not work and give you error similar to what you get
less_than(f1(), f2()) # Call-2: this works
Call-1 passes the function itself, whereas Call-2 passes result of f1() and f2(), which are integers and can be compared by <.
In the code the main() needs to be rewritten like this:
def main(): #Function to call all functions in the program
r = random_int(1000)
n = new_guess()
high_low(r, n)
win()
Error-2
After above fix, executing will give another error:
NameError: name 'guess' is not defined
It means guess has not been defined. That's fixed by re-writing high_low() again like this. Notice the name new_guess replaced with guess. One is the function and other is the variable.
def high_low(random_int, guess): #Lets the user know if the number they guessed is too high or too low
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
guess = new_guess()
Error-3
Again running would give this error:
TypeError: '>' not supported between instances of 'str' and 'int'
Fix is simple, the new_guess() function needs to convert input to int as calling input returns everything as string.
def new_guess(): #Prompts the user to enter an integer as their guess
guess = int(input("Enter your guess (between 1 - 1000): "))
return guess
Error-4
Last error would be:
UnboundLocalError: local variable 'attempts' referenced before assignment
This simply means no value has been set to attempts before using it in attempts += 1
This gets fixed again by updating high_low and adding attempts = 0:
def high_low(random_int, guess): #Lets the user know if the number they guessed is too high or too low
attempts = 0
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
guess = new_guess()
Final code looks like this:
from random import randrange
#Initialize variables
attempts = 0
def random_int(size): #Generates a random integer from given parameters (size)
return randrange(1, size+1)
def new_guess(): #Prompts the user to enter an integer as their guess
guess = int(input("Enter your guess (between 1 - 1000): "))
return guess
def high_low(random_int, guess): #Lets the user know if the number they guessed is too high or too low
attempts = 0
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
guess = new_guess()
def win(random_int, new_guess): #Prints that the answer is correct, along with the number of guesses it took
while guess == random_int:
if attempts >= 2: #If it took the user more than 1 attempt, uses "guesses" for proper grammar
print("You guessed the correct number, you win! It took you ", str(attempts()), " guesses.")
input("Would you like to play again? (Y/N): ")
if input == Y: #If user inputs "Y", runs the program again
main()
elif input == N: #If user inputs "N", terminates the program
break
elif attempts < 2: #If it took the user only 1 attempt, uses "guess" for proper grammar
print("You guessed the correct number, you win! It took you ", str(attempts()), " guess.")
input("Would you like to play again? (Y/N): ")
if input == Y: #If user inputs "Y", runs the program again
main()
elif input == N: #If user inputs "N", terminates the program
break
def main(): #Function to call all functions in the program
r = random_int(1000)
n = new_guess()
high_low(r, n)
win()
main() #Calls the "main" function, runs the program
your high_low function has no reference to a variable named guess. I think the solution is to just add the line guess = new_guess() right before the while loop.
I need help changing the range and showing the user what the range is so they know if they are closer or not. I have given the description I have been given. On what I need to do . I have given the code that I have come up wit so far. Let me know if you need anything else from me.
Step 6 – Guiding the user with the range of values to select between
Add functionality so that when displaying the guess prompt it will display the current range
to guess between based on the user’s guesses accounting for values that are too high and too
low. It will start out by stating What is your guess between 1 and 100, inclusive?, but as
the user guesses the range will become smaller and smaller based on the value being higher
or lower than what the user guessed, e.g., What is your guess between 15 and 32,
inclusive? The example output below should help clarify.
EXAMPLE
----------------
What is your guess between 1 and 44 inclusive? 2
Your guess was too low. Guess again.
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
play()
#Part 1
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.")
print("\n")
def play():
''' Plays a guessing game'''
number = int(random.randrange(1,10))
guess = int(input("What is your guess between 1 and 10 inclusive ?: "))
number_of_guess = 0
while guess != number :
(number)
#Quit
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
#Guessing
if guess < number:
if guess < number:
guess = int(input("Your guess was too low. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
if guess > number:
if guess > number:
guess = int(input("Your guess was too high. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
#Winner
if guess == number :
number_of_guess += 1
print("Congratulations you won in " + str(number_of_guess) + " tries!")
again()
def again():
''' Prompts users if they want to go again'''
redo = input("Do you want to play again (Y or N)?: ")
if redo.upper() == "Y":
print("OK. Let’s play again.")
play()
elif redo.upper() == "N":
print("OK. Have a good day.")
sys.exit(0)
else:
print("I’m sorry, I do not understand that answer.")
again()
main()
What you'll need is a place to hold the user's lowest and highest guess. Then you'd use those for the range checks, instead of the hardcoded 1 and 11. With each guess, if it's a valid one, you then would compare it to the lowest and highest values, and if it's lower than the lowest then it sets the lowest value to the guess, and if it's higher than the highest it'll set the highest value to the guess. Lastly you'll need to update the input() string to display the lowest and highest guesses instead of a hardcoded '1' and '10'.
You need to simplify a lot your code. Like there is about 6 different places where you ask a new value, there sould be only one, also don't call method recursivly (call again() in again()) and such call between again>play>again.
Use an outer while loop to run games, and inside it an inner while loop for the game, and most important keep track of lower_bound and upper_bound
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
redo = "Y"
while redo.upper() == "Y":
print("Let’s play")
play()
redo = input("Do you want to play again (Y or N)?: ")
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.\n")
def play():
lower_bound, upper_bound = 0, 100
number = int(random.randrange(lower_bound, upper_bound))
print(number)
guess = -1
number_of_guess = 0
while guess != number:
guess = int(input(f"What is your guess between {lower_bound} and {upper_bound - 1} inclusive ?: "))
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
elif guess not in list(range(lower_bound, upper_bound)):
print("You're outside the range")
continue
number_of_guess += 1
if guess < number:
print("Your guess was too low")
lower_bound = guess
elif guess > number:
print("Your guess was too high")
upper_bound = guess
print("Congratulations you won in", number_of_guess, "tries!")
I'm having an issue with my program. I'm working on a program that lets you play a small game of guessing the correct number. The problem is if you guess the correct number it will not print out: "You guessed it correctly". The program will not continue and will stay stuck on the correct number. This only happens if you have to guess multiple times. I've tried changing the else to a break command but it didn't work.
Is there anyone with a suggestion?
This is what I use to test it:
smallest number: 1
biggest number: 10
how many times can u guess: 10
If you try to guess the correct number two or three times (maybe more if u need more guesses) it will not print out you won.
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
guess = int(input("guess the number: "))
#while loop until the guess is the same as the random number
while guess != x:
#this is if u guessed to much u get the error that you've guessed to much
while count < amount:
if guess > x:
print("this is not the correct number, the correct number is lower \n")
guess = int(input("guess the number: "))
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
guess = int(input("guess the number: "))
count += 1
else: print("\n \nYou Lost, You've guessed", x, "times\n")
break
#this part is not working, only if you guess it at the first time. it should also print this if you guessed it in 3 times
else: print("You guessed it correctly", x)
test = (input("this is just a test if it continues out of the loop "))
print(test)
The main issue is that once guess == x and count < amount you have a while loop running that will never stop, since you don't take new inputs. At that point, you should break out of the loop, which will also conclude the outer loop
You can do it simply by using one while loop as follows:
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
#this is if u guessed too much u get the error that you've guessed too much
while count <= amount:
guess = int(input("guess the number: "))
if guess > x:
print("this is not the correct number, the correct number is lower \n")
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
count += 1
else:
print("You guessed it correctly", x)
break
if guess!=x:
print("\n \nYou Lost, You've guessed", count, "times\n")
As Lukas says, you've kind of created a situation where you get into a loop you can never escape because you don't ask again.
One common pattern you could try is to deliberately make a while loop that will run and run, until you explicitly break out of it (either because the player has guessed too many times, or because they guessed correctly). Also, you can get away with only asking for a guess in one part of your code, inside that while loop, rather than in a few places.
Here's my tweak to your code - one of lots of ways of doing what you want to:
import random
#counts the mistakes
count = 0
#asks to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#asks how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
#while loop until the guess is the same as the random number
while True:
if count < amount:
guess = int(input("guess the number: "))
#this is if u guessed to much u get the error that you've guessed to much
if guess > x:
print("this is not the correct number, the correct number is lower \n")
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
count += 1
else:
print("You guessed it correctly", x)
break
else:
print("\n \nYou Lost, You've guessed", x, "times\n")
PS: You got pretty close to making it work, so nice one for getting as far as you did!
This condition is never checked again when the guessed number is correct so the program hangs:
while guess != x:
How about you check for equality as the first condition and break out of the loop if true:
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
guess = int(input("guess the number: "))
if guess == x:
print("You guessed it correctly", x)
else:
while count < amount:
if guess > x:
print("this is not the correct number, the correct number is lower \n")
guess = int(input("guess the number: "))
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
guess = int(input("guess the number: "))
count += 1
else:
print("You guessed it correctly", x)
break
else:
print("You guessed too many times")
I am working on a guessing game in python, i think i have everything only, i want to make the program to guess between numbers it already guessed for example, if the users number is 5, and it picks 3 the user input '+' and it knows the number is higher, and if the program guess 6 the user input '-' and it knows the number is lower than 6, but sometimes it guesses a 2, its obvious that if the number is higher than 3 it can't possibly be 2 right, so how do i write that? I am a beginner at this and i would appreciate if you could make it simple, below is my code.
print("Hello,")
print("welcome to the guessing game")
print('I shall guess a number between 1 and 99, and then ask you if am right')
print('I have a maximum of 20 chances\n')
import random
guess = random.randint(1,99)
print("Your number is %f, Am i right?" % guess)
print('If I am, enter =, If the number is higher enter (+), if the number is lower enter (-)')
ans = input('Which is it: ')
print("You chose %s" % ans)
minguess = 1
maxguess = 99
count = 0
while (count < 20):
count = count + 1
if ans == '+':
##I am using these prints to keep track of the numbers and if everything is working correctly
maxguess1 = guess + 1
print('THe maxguess is', maxguess1)
newguess = random.randint(maxguess1, maxguess)
print('The newguess is', newguess)
newguess = int(newguess)
print("Is it %d?" % newguess)
print('If I am, enter =, If the number is higher enter (+), if the number is lower enter (-)')
ans = input('Which is it: ')
elif ans == "-":
maxguess2 = guess - 1
print('The minus maxguess is', maxguess2)
newguess = random.randint(minguess, maxguess2)
print('The minus newguess is', newguess)
newguess1 = int(newguess)
print("Is it %d?" % newguess1)
print('If I am, enter =, If the number is higher enter (+), if the number is lower enter (-)')
ans = input('Which is it: ')
if ans == "=":
print('YAAAAAAS MAN')
i wanted it to change the numbers whenever it guessed a new number
guess = newguess
NOTE: This example is in Python 2.7, NOT Python 3, but the concepts are the same.
Break down the problem into its individual elements:
import random
# Possible Range is [1-99], 1 inclusive to 99 inclusive
min_possible = 1
max_possible = 99
# Number of Guesses
max_guesses = 20
# Process
for i in xrange(max_guesses): # Loops through the process 'max_guesses' times
# Program Takes a Guess
guess = random.randint(min_possible, max_possible)
print 'My guess is ' + str(guess)
# Ask for User Feedback
user_feedback = ''
while not user_feedback in ['+', '-', '=']:
user_feedback = raw_input('Is the number higher (+), lower (-), or equal (=) to my guess?')
# Use the User Feedback
if user_feedback == '+':
min_possible = guess + 1 # B/c low end is inclusive
elif user_feedback == '-':
max_possible = guess - 1 # B/c high end is inclusive
else:
print 'I knew the answer was ' + str(guess)
break
I'm working my way through the Code Academy Python course and have been trying to build small side projects to help reinforce the lessons.
I'm currently working on a number game. I want the program to select a random number between 1 and 10 and the user to input a guess.
Then the program will return a message saying you win or a prompt to pick another higher/lower number.
My code is listed below. I can't get it to reiterate the process with the second user input.
I don't really want an answer, just a hint.
import random
random.seed()
print "Play the Number Game!"
x = raw_input("Enter a whole number between 1 and 10:")
y = random.randrange(1, 10, 1)
#Add for loop in here to make the game repeat until correct guess?
if x == y:
print "You win."
print "Your number was ", x, " and my number was ", y
elif x > y:
x = raw_input("Your number was too high, pick a lower one: ")
elif x < y:
x = raw_input("Your number was too low, pick a higher one: ")
You need use a while loop like while x != y:. Here is more info about the while loop.
And you can only use
import random
y = random.randint(1, 10)
instead other random function.
And I think you should learn about int() function at here.
These are my hints :)
import random
n = random.randint(1, 10)
g = int(raw_input("Enter a whole number between 1 and 10: "))
while g != n:
if g > n:
g = int(raw_input("Your number was too high, pick a lower one: "))
elif g < n:
g = int(raw_input("Your number was too low, pick a higher one: "))
else:
print "You win."
print "Your number was ", g, " and my number was ", n