Python- Stuck on a guessing game's program? - python

So, I've been working on this guessing game problem for a while and I am left scratching my brain for the past 2 hours trying to figure out what's wrong but I can't. I also tried searching for the solution but I don't wanna do copy & paste and I actually want to solve my code by myself.
Here's what I've been able to get so far:
start = 0
end = 100
print 'Please think of a number between 0 and 100!'
user = ''
ans = (start + end) / 2
while user != 'c':
print ('Is your secret number ' + str((start + end) / 2) + '?')
user = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")
if user == 'l':
start = ans
elif user == 'h':
end = end - ans
ans = start
print 'Game over. Your secret number was: ' + str((start + end) / 2)
What am I doing wrong?
Edit: The game should run something like this:
Please think of a number between 0 and 100!
Is your secret number 50?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
Is your secret number 75?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
Is your secret number 87?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. h
Is your secret number 81?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
Is your secret number 84?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. h
Is your secret number 82?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
Is your secret number 83?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. c
Game over. Your secret number was: 83

You are settings ans = start, thats the mistake. Since you want to solve this yourself, I will not further explain things. This is what causes your program to never decrease below 25:
Please think of a number between 0 and 100!
Is your secret number 50?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. h
Is your secret number 25?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. h
Is your secret number 25?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. h
Is your secret number 25?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. h
Is your secret number 25?

I see two problems with your current code. First of all, you are never changing ans within the loop. You probably want to have ans contain the number that is the current guess. So you should set it whenever you do a guess and use it in the ouput directly. So move the ans = (start + end) / 2 line at the beginning of the loop.
The second problem, is that you set end = end - ans when the guess was too high. While this works most of the times as you are using binary search and always guess in halves, it is not really what you want to do. If you want to search in the range [start, end] then you should set end to the highest number that is still available for guessing; that would be ans - 1 when you guessed too high.
Lastly, you probably want to catch the situation where start == end. In this case, either you have found the number, or the user has entered some wrong stuff.
Also as a general tip, printing out intermediary results can help a lot when debugging. For example you could put a print(start, end) at the top of your loop to see the range you are looking at during each guess. Then you would have easily noticed, that the beginning of the range never changed.

My solution works:
import random
numH = 100
numL = 0
num = random.randint(numL, numH)
print num
x = raw_input('Enter high, low or number 1: ')
while x == 'l' or x == 'h':
if x == 'l':
numH = num - 1
num = random.randint(numL, numH)
print num
x = raw_input('Enter high, low or number 2: ')
if x == 'h':
numL = num + 1
num = random.randint(numL, numH)
print num
x = raw_input('Enter high, low or number 2: ')
else:
print 'your number is ', num

Related

what is causing reference before assignment errors in below code?

I'm getting this error with refrenced before assignment and im not sure how to fix it.
I havent tried anything at the moment. It would be appreciated if this could be answered. (im just trying to fill up more words so it can be posted)
this is the error code i am getting:
number = int(number)
UnboundLocalError: local variable 'number' referenced before assignment
And this is the rest of my code
import random
import sys
again = True
while True:
myName = input('Hello, Enter your name to get started')
if myName.isdigit():
print('ERROR,Your Name is not a number, please try again')
print('')
continue
break
myName = str(myName.capitalize())
print('')
print('Hi {}, This is Guessing Game, a game where you have a certain amount of attempts to guess a randomly generated number. Each level has a different amount of attempts and a higher range of number. After each guess, press enter and the program will determine if your guess is correct or incorrect.' .format (myName))
print('--------------------------------------------------------------------------------')
while True:
level = input('{}, Please select a level between 1 and 3. Level 1 being the easiest and 3 being the hardest')
if not level.isdigit():
print('Please enter a number between 1 and 3. Do not enter a number in word form')
continue
break
def guessNumber(): # Tells the program where to restart if the user wants to play again
guessesTaken = 0
List = []
if level == 1:
number = random.randint (1, 16)
print('You chose Level 1, Guess a number a between 1 and 16, you have 6 guesses.')
allowedGuesses = 6
boundary = 16
if level == 2: # The code for level 2
number = random.randint (1,32)
print('You chose Level 2, Guess a number between 1 and 32, You have 8 guesses.')
allowedGuesses = 8
boundary = 32
if level == 3:
number = random.randint (1, 40)
print('You chose Level 3, Guess a number between 1 and 40, you have 10 guesses.')
allowedGuesses = 10
boundary = 40
if level == 4:
number = random.randint (1, 50)
print('You chose Level 4, Guess a number between 1 and 50, you have 10 guesses.')
allowedGuesses = 10
boundary = 50
if level == 5:
number = random.randint (1, 60)
print('You chose Level 5, Guess a number between 1 and 60, you have 10 guesses.')
allowedGuesses = 10
boundary = 60
guess = input()
guess = int(guess)
while guessesTaken < allowedGuesses:
guessesTaken = guessesTaken + 1
guessesLeft = allowedGuesses - guessesTaken
if guess < number:
List.append(guess)
print('Your guess is too low, You must guess a higher number, you have {} guesses remaining. You have guessed the numbers {}, Take another guess' .format (guessesLeft, List))
if guess > number:
List.append(guess)
print('Your guess is too high, You must guess a lower number, you have {} guesses remaining. You have guessed the numbers {}, Take another guess' .format (guessesLeft, List))
if guess > boundary:
List.append(guess)
print('You must input a number between 1 and 16. You have {} guesses remaining. You have guessed the numbers {}, Take another guess' .format (guessesLeft, List))
if guess == number:
List.append(guess)
print('Good Job {}!, You guessed my number in {} guesses. You guessed the numbers {}.' .format (myName, guessesTaken, List))
print('Your high score for your previous game was {}' .format(guessesTaken))
else:
number = int(number)
print('')
print('--------------------------------------------------------------------------------')
print('Sorry {}, Your gueses were incorrect, The number I was thinking of was {}. You guessed the numbers {}.' .format(myName, number, List))
guessNumber()
print('')
print('It is recommended to pick a harder level if you chose to progress')
print('')
while True:
again = input('If you want to play again press 1, if you want to stop playing press 2')
if not again.isdigit():
print('ERROR: Please enter a number that is 1 or 2. Do not enter the number in word form')
continue
break
if again == 1:
level + 1
guessNumber()
if again == 2:
print('Thanks for playing Guessing Game :)')
sys.exit(0)
In your code you are getting level as input and checking that if level is in between 1 to 5.
else you are trying number = int(number)
but you should write number = int(level).
Since level is a string rather than a number, none of the conditions like
if level == 1:
will succeed. So none of the assignments like number = random.randint (1, 16) ever execute, and number is never assigned.
Since if level == 5: doesn't succeed, it goes into the else: block, which starts with
number = int(number)
Since none of the other number assignments took place, this tries to use int(number) before the variable has been assigned, which doesn't work.
I'm not sure why you even have this assignment there. When number is assigned, it's always set to an integer, so there's no need to use int(number).
You need to use
level = int(level)`
after you confirm that it contains digits. And you need to do similarly with again.
There are a number of other problems with your code. For instance, the code that asks for the user's guess and checks it is inside the if level == 5: block, it should run in all the levels.
When you have a series of mutually exclusive tests, you should use elif for each successive test. If you just use if for each of them, and then use else: at the end, that else: will only apply to the last test, so it will be executed even if one of the early tests also succeeded.

Store numbers and compare based on user input

Currently working to learn Python 3.5 from scratch and thoroughly enjoying the process. latest thing is to write a basic program that does the following..
Asks user to think of a number between 1 and 100
Guesses what it is
Asks user to enter '1' if too low, '3' if too high and '2' if
correct
Provides a new number based on that user input
Limits itself to 10 tries before quitting in shame
Celebrates when it gets it right
Now I THINK I've got it all working minus the higher / lower feature. My question is this.
Note This differs from other questions on the topic because I do not want to enter any numbers for the PC to work on. Also want to generate pseudo-random numbers that are limited to within given values for subsequent guesses from the PC. Not increment.
"How can I implement a feature that looks at the var 'guess' and modifies it to be higher or lower based on user input while keeping it above 0 and below 100".
Code:
import random
print("\tWelcome to the psychic computer")
print("\nI want you to think of a number between 1 and 100.")
print("I will try to guess it in 10 or less tries.\n")
print("\n Press 1 for a lower guess, 3 for a higher one and 2 if I get it right\n")
tries = int(1)
guess = random.randint(1, 100)
print("\nI guess ", + guess, " Is this correct?")
while tries < 10:
feedback = int (input("\nEnter 1 if too high, 3 if too low or 2 if bang on\n\n"))
tries += 1
if feedback == 1:
print("Balls! Guess I need to go Higher will", + guess, + "do?")
elif feedback == 3:
print("\nSh*te! Lower it is then...")
elif feedback == 2:
print("YEEAAAHH BOYEEEE! Told you I was phychic.")
input("\nHit enter to quit")
end
elif feedback != (1,2,3):
print("Not a valid guess. Try again.")
break
if tries >= 9:
print("\nSh*t, guess I'm not so psychic after all")
input("\nHit enter to exit")
You could do something like a binary search. Use a low_number and a high_number to calculate a guess by taking the middle value of the two. These can initially be set 0 and 100. You should also keep track of your last guess. If you last guess was too low, you can set your low_number equal to that guess+1. If your last guess was too high, you can set your high_number to that guess-1.
OK this is what I have so far. It works in that it will respond with (semi) random higher or lower guesses based on user input but does not yet store the original guess as a reference. I will look at that tomorrow. Thanks again for the suggestions.
BTW once working I plan to use math and come up with a solution that always gets it right inside x amount of tries..
import random
print("\tWelcome to the psychic computer")
print("\nI want you to think of a number between 1 and 100.")
print("I will try to guess it in 10 or less tries.\n")
print("\n Press 1 for a higher guess, 3 for a lower one and 2 if I get it right\n")
tries = int()
guess = random.randint(1, 100)
high_number = int(100 - guess)
low_number = int(1 + guess)
print("\nI guess ", + guess, " Is this correct?")
while tries < 10:
feedback = int (input("\nEnter 1 to go higher, 3 to go lower or 2 if bang on\n\n"))
tries += 1
if feedback == 1:
guess = random.randint(high_number, 100)
print("Balls! Guess I need to go Higher how about", + guess)
elif feedback == 3:
guess = random.randint(1, low_number)
print("\nSh*te! Lower it is then... what about", + guess)
elif feedback == 2:
print("YEEAAAHH BOYEEEE! Told you I was phychic.")
input("\nHit enter to quit")
end
elif feedback != (1,2,3):
input("Not a valid guess. Try again.")
break
if tries >= 9:
print("\nSh*t, guess I'm not so psychic after all")
input("\nHit enter to exit")

High Low: Computer guesses your number

all. I'm quite new to programming, and I'm trying to figure out why my code isn't working properly. It runs fine up until you tell the computer whether or not its first guess is too high (h), or too low (l). If, say, the guess is too high, and tell the computer that, each guess after will continue guessing lower, regardless of whether or not you enter too low (l). It happens the other way around as well. Hopefully someone can help. Here's the code!
import random
import time
print "Think of a number between 1 and 100 and I'll try and guess it."
time.sleep(2)
print "Let me know if my guess is too (h)igh, too (l)ow, or (c)orrect."
time.sleep(2)
guess = int(raw_input("Pick your number between 1-100: "))
low = 1
high = 100
tries = 0
compguess = random.randrange(low, high)
h = compguess > guess
l = compguess < guess
c = compguess == guess
while compguess != guess:
tries += 1
print "Is it", compguess
if h:
raw_input ()
new_high = (compguess - 1)
compguess = random.randint(low, new_high)
elif l:
raw_input ()
new_low = (compguess + 1)
compguess = random.randint(new_low, high)
elif c:
raw_input ()
print("The computer guessed your number of: ", guess)
Forgive the spacing. I'm not quite sure how to copy it properly.
The raw_input() function returns a value. If you don't assign the return value to a variable or otherwise do something with it, the value returned is simply discarded by Python.
You probably want something like:
print "Is it", compguess
answer = raw_input()
if answer == "h":
...
elif answer == "l":
...
That way, you prompt the user for input, wait for the user to type something, then act upon what the user typed.
You also don't need the h, l, or c local variables. They don't actually serve a purpose in your code.
Finally, why do you ask the user to tell the computer what number the user is thinking of? Isn't the point of this exercise to get the computer to guess the user's number, without knowing what the result is?

Display Variable value in Python using print Statement?

I have created a Python program that guesses the number programmer thinks in mind. Everything is working file but i don't know how to use guess in print statement in a way that print statement display number as well. I tried adding word "guess" but it is not working. I am C programmer and working with Python for the first time, so i am unable to figure it out.
hi = 100
lo = 0
guessed = False
print ("Please think of a number between 0 and 100!")
while not guessed:
guess = (hi + lo)/2
print ("Is your secret number " + //Here i need to Display the guessed Number + "?")
user_inp = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too"
"low. Enter 'c' to indicate I guessed correctly: ")
if user_inp == 'c':
guessed = True
elif user_inp == 'h':
hi = guess
elif user_inp == 'l':
lo = guess
else:
print ("Sorry, I did not understand your input.")
print ("Game over. Your secret number was: " + //Here i need to display final number saved in guess.)
Just convert it to string.
print ("Game over. Your secret number was: " + str(guess))
You could also use string formatting.
print("Game over. Your secret number was {}".format(guess))
Or, since you come from a C background, old style string formatting.
print("Game over. Your secret number was %d." % guess)
Try this in your print statement and let me know if it works.
str(guess)
Python has very nice string formatting, which comes in handy when you need to insert multiple variables:
message = "Game over after {n} guesses. Your number was {g} (pooh... got it in {n} times)".format(g=guess, n=number)
print(message)

Python: Unexpected conditional activation in simple bisection search game

I'm wrote some code to determine a secret number between 0 and 100. The user tells the machine the guessed number (which is half the range) is either to high, too low or just right. Based on the input, the machine used bisection search to adjust the guess. When the guess is correct, the user presses c and the game ends. The problem is, in spite of the conditions placed in the 'i did not understand input' branch, this branch triggers when the user presses c ( a valid entry) and it is not the first guess.
for example, here is the output-
Please think of a number between 0 and 100!
Is your secret number 50?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
Is your secret number 75?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. c
Sorry, I did not understand your input.
Game over. Your secret number was:75
>>>
And here is the code-
High=100
Low=0
Guess=50
user_input=0
print('Please think of a number between 0 and 100!')
while user_input != 'c':
print("Is your secret number"+" "+str(Guess)+"?")
userinput = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
if user_input == 'h':
High=Guess
Guess= ((High+Low)/2)
if user_input == 'l':
Low=Guess
Guess= ((High+Low)/2)
if user_input != 'h' or 'l' or 'c':
print('Sorry, I did not understand your input.')
print ('Game over. Your secret number was:'''+ str(Guess))
Thanks in advance. I'v been wracking my head over this for hours....
Try this instead for that conditional.
if user_input not in ['h','l','c']:
print('Sorry, I did not understand your input.')
You probably don't have to check if user_input is h or l since the first couple of if should handle that.
if user_input == 'h':
High=Guess
Guess= ((High-Low)/2)
elif user_input == 'l':
Low=Guess
Guess= ((High-Low)/2)
elif user_input == 'c':
pass # the while statement will deal with it or you could break
else:
print('Sorry, I did not understand your input.')
Conditionals don't work like that. You need something like:
# Check each condition explicitly
if user_input != 'h' and user_input != 'l' and user_input != 'c':
Or:
# Check if the input is one of the elements in the given list
if user_input not in ["h", "c", "l"]:
Your current approach is understood as
if (user_input != 'h') or ('l') or ('c'):
And since l and c are truthy, that branch will always execute.
You might also consider using elif, so your conditions would become the following:
while True:
if user_input == 'h':
High=Guess
Guess= ((High-Low)/2)
elif user_input == 'l':
Low=Guess
Guess= ((High-Low)/2)
elif user_input == "c":
# We're done guessing. Awesome.
break
else:
print('Sorry, I did not understand your input.')
Other than your if, your logic has a few errors. I'd recommend something like this:
High = 100
Low = 1
LastGuess = None
print('Please think of a number between 0 and 100!')
while True:
Guess = int((High+Low)/2)
if Guess == LastGuess:
break
print("Is your secret number"+" "+str(Guess)+"?")
user_input = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
if user_input == 'h':
High = Guess
LastGuess = Guess
elif user_input == 'l':
Low = Guess
LastGuess = Guess
elif user_input == 'c':
break
else:
print('Sorry, I did not understand your input.')
print ('Game over. Your secret number was:'''+ str(Guess))

Categories

Resources