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))
Related
The following project requires: Your program should implement a simple guessing game with the following requirements:
Generate a random number between 1 and 50 and then have the user guess the number. The program should tell the user whether they have guessed too high or too low and allow them to continue to guess until they guess the number or enter a 0 to quit.
When they guess the number it should tell them how many guesses it took. At the end, the program should ask them if they want to play again.
For example:
Enter a guess 1-50, or 0 to quit: 25
Too high!
Enter a guess 1-50, or 0 to quit: 15
Too low!
Enter a guess 1-50, or 0 to quit: 100
Guess must be between 1 and 50!
Enter a guess 1-50, or 0 to quit: 18
That's it! You took 3 guesses to get the number.
Would you like to play again? (Y/N)
I currently have everything settled except for two issues. I cannot seem to get the play again feature to work and for some reason the first number that is guessed will not say whether it is too low or too high.
My following code:
import random
play = True
randomNum = 45 #random.randrange(1,50)
guesses = 1
num = int(input())
print("Enter a guess 1-50, or 0 to quit:", num)
if num > 50 or num < 1:
print('Guess must be between 1 and 50!')
if num == randomNum:
print("That's it! You took", guesses, "guess to get the number.")
#print("Guess must be between 1 and 50!")
while num != randomNum:
guesses += 1
num = int(input())
print("Enter a guess 1-50, or 0 to quit:", num)
if num == 0:
break
elif num > 50 or num < 1:
print('Guess must be between 1 and 50!')
elif num > randomNum:
print("Too high!")
elif num < randomNum:
print("Too low!")
if num == randomNum:
print("That's it! You took", guesses, "guesses to get the number.")
print("Would you like to play again? (Y/N)")
letter = str(input())
if letter != 'Y':
play = False
I explained above what I have tried. I do believe that the issue is that the first guess does not enter the while loop. Unsure of how to fix this though.
First issue is that your while cycle only lasts until a number is guessed. So that means after you guess the first random number, your program will finish.
In order to avoid that you should declare your $play = True$ boolean on top of the cycle so you can declare your while cycle something like this:
play = True
while play:
# game goes here.
print("Would you like to play again? (Y/N)")
letter = str(input())
if letter != 'Y':
play = False
Then your cycle should continue while letter is Y or play remains True.
Second issue is that you ask for the number outside the cycle. That is not necessary, you can ask it inside after you construct your code like the example above.
I hope this clears things up.
ps. This is my first answer, so please point out if I did something wrong!
I think the problem is the loop is not ending even when the right number is input. However, the line (while choice != a :) should prevent that, so I'm not sure what's wrong.
import random
a = random.randint(1, 9)
choice = int(input("give me a number"))
while choice != a :
if choice > a:
choice = int(input("You guessed too high. Please guess again"))
elif choice < a:
choice = int(input("You guessed to low. Please guess again"))
print("You won")
I'm making a simple guessing game in python and was trying to create an "Invalid entry" message for when the user enters in any input that is not an integer.
I have tried to use just 'int' in an if statement to address all integers, but that is not working.
I know that I have the syntax wrong. I'm just not sure what the correct syntax to do it would be.
import random
play = True
while play:
count = 1
hidden = random.randrange(1,5)
guess = int(input("Guess a number between 1 and 5:"))
if guess != int
guess = int(input("Invalid Entry. Please enter an Integer between 1 and 5:"))
while guess != hidden:
count+=1
if guess > hidden + 10:
print("your guess is to high!")
elif guess < hidden -10:
print("your too low!")
elif guess > hidden:
print("your really warm, but still to high!")
elif guess < hidden:
print("your really warm, but still to low")
print("You have guessed incorrectly, Try again!. \n")
#reset the guess variable and make another guess
guess = int(input("Guess a number between 1 and 5:"))
print("Nice!!! Your guess was correct!\n you got the correct number in" , count , "tries.")
count = 1
playagain = str(input("Do you want to play again?\nType yes or no: "))
if playagain == "no" or "n" or "N" or "no thank you":
play = False
elif playagain == "yes" or "y" or "Y" or "YES" or "yes":
play = True
else: playagain != "yes" or "y" or "Y" or "YES" or "yes" "no" or "n" or "N" or "no thank you"
playagain = str(input("Invalid Entry. Please Type yes or no: "))
This is the error that I'm getting. There may be some other mistakes in my code as well.
File "comrandomguess.py", line 18
if guess != int
^
SyntaxError: invalid syntax
If you really want to verify that the user entry is an int, you want to keep the input in string form. Then write a small function to test the input. Here, I'll use a list comprehension and the string join and isdigit methods, to ensure the user has only entered digits 0-9 in the string, i.e. then this function returns True (else False) (*modified as per Jack Taylor comment below, also for s = '' case):
def testForInt(s):
if s:
try:
_ = s.encode('ascii')
except UnicodeEncodeError:
return False
test = ''.join([x for x in s if x.isdigit()])
return (test == s)
else:
return False
If you want to sandbox the user entirely, wrap it in a loop like this:
acceptable = False
while not acceptable:
entry = input("Enter an int: ")
if testForInt(entry):
entry = int(entry)
acceptable = True
else:
print("Invalid Entry")
If you want a simpler version with no function call(see Jack Taylor comment), this works too:
acceptable = False
while not acceptable:
entry = input("Enter an int: ")
try:
entry = int(entry)
acceptable = True
except ValueError as e:
print(f"Failed due to {str(e)}")
Now you've got what you know is an int, with no worries. This kind of approach to verifying user entry saves many headaches if consistently implemented. See SQL injection etc.
I always use this method to check if something is not an integer:
Python 3
if not round(guess) == guess: print("Do Stuff")
Python 2
if not round(guess) == guess: print "Do Stuff"
You need to do something like this:
play = True
while play:
guess = input("Guess a number between 1 and 5: ")
try:
number = int(guess)
except ValueError:
print("You need to input an integer.")
continue
if number < 1 or number > 5:
print("You need to input an integer between 1 and 5.")
continue
# ...
print("Your number was: " + guess)
play = False
When you first use input(), you get a string back. If you try to turn that string into an integer straight away by doing int(input()), and if the player types a string like "abcd", then Python will raise an exception.
>>> int(input("Guess a number: "))
Guess a number: abcd
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abcd'
To avoid this, you have to handle the exception by doing int(guess) inside a try/except block.
The continue statement skips back to the start of the while loop, so if you use it you can get away with only having to ask for input once.
Parse the user input as string to avoid ValueError.
guess = input("Guess a number between 1 and 5: ")
while not guess.isdigit() or int(guess) > 5 or int(guess) < 1:
guess = input("Invalid Entry. Please enter an Integer between 1 and 5: ")
guess = int(guess)
Above code ensures that user input is a positive integer and between 1 and 5. Next, convert the user input to integer for further use.
Additionally, if you want to check the data type of a python object/variable then use the isinstance method. Example:
a = 2
isinstance(a, int)
Output:
>>> True
In Codeacademy, I ran this simple python program:
choice = raw_input('Enjoying the course? (y/n)')
while choice != 'y' or choice != 'Y' or choice != 'N' or choice != 'n': # Fill in the condition (before the colon)
choice = raw_input("Sorry, I didn't catch that. Enter again: ")
I entered y at the console but the loop never exited
So I did it in a different way
choice = raw_input('Enjoying the course? (y/n)')
while True: # Fill in the condition (before the colon)
if choice == 'y' or choice == 'Y' or choice == 'N' or choice == 'n':
break
choice = raw_input("Sorry, I didn't catch that. Enter again: ")
and this seems to work. No clue as to why
You have your logic inverted. Use and instead:
while choice != 'y' and choice != 'Y' and choice != 'N' and choice != 'n':
By using or, typing in Y means choice != 'y' is true, so the other or options no longer matter. or means one of the options must be true, and for any given value of choice, there is always at least one of your != tests that is going to be true.
You could save yourself some typing work by using choice.lower() and test only against y and n, and then use membership testing:
while choice.lower() not in {'n', 'y'}:
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