Why does my string comparison fail on the first test? - python

If I enter, h or l, c It keeps prompting me to enter a number instead of going to the correct case.
print("Please think of a number between 0 and 100! ");
low = 0;
high = 100
mid = 50
while True:
print("Is your secret number " + str(mid) + "?")
guess = 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 (guess != "h") or (guess != "l") or (guess != "c"):
print "Sorry, I did not understand your input."
print "Is your secret number %i?" % mid
guess = 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.")
elif guess == 'l':
low = mid
elif guess == 'h':
high = mid
else:
print "Game over. Your secret number was: %c" % mid
break
mid = (high + low) / 2

Your condn exp is wrong, it should be
if (guess != "h") and (guess != "l") and (guess != "c"):
This means that if the value is not h and l and c then execute. Your statement instead implied that if the input is not h or l or c then execute. So when you give h as input it fails as it is not l and c
Or as mentioned in a comment, you can instead do,
if guess not in ['h', 'l', 'c']:

Related

Input not mapping with the elif clause

I am new to learning python and programming in general. I wrote this code for computer to guess a number that i imagined (in between 1 to 100). It is showing me the same output "Sorry, I did not understand your input." which is applicable only if my input doesnot match l, h or c. In cases where my input is l,h or c, it should take those conditions and follow up to finally reach to an outcome. But that isn't happening.I am trying to use bisection method. Can you please help me where is it going wrong ?
num_begin = 0;
num_end = 100;
avg=(num_begin+num_end)/2
print("Please think of a number between 0 and 100!")
print("is your secret number "+ str(avg))
command=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")
while (True):
if (command != 'c' or command != 'h' or command != 'l'):
print("Sorry, I did not understand your input.")
print("is your secret number "+ str(avg))
command=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")
elif(command=='l'):
num_begin=avg
avg=(num_begin+num_end)/2
print("is your secret number "+ str(avg))
command=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")
elif(command=='h'):
num_end=avg
avg=(num_begin+num_end)/2
print("is your secret number "+ str(avg))
command=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")
else:
print("Game over. Your secret number was: " + str(avg))
break
Just replace or by and in your first condition
if (command != 'c' and command != 'h' and command != 'l'):

Python 3: Traceback : TypeError

I'm new in python 3 and I don't understand why I get a Type Error (this is a guess a number game for numbers between 0-100):
print("Please think of a number between 0 and 100!")
low = 0
high = 100
check = False
while True :
guess = (low + high)/2
print("Enter 'h' to indicate the guess is too high.\n")
print("Enter 'l' to indicate the guess is too low.\n" )
print("Enter 'c' to indicate I guessed correctly.\n")
ans = input("")
if ans == "h" :
low = ans
elif ans == "l" :
high = ans
elif ans =="c" :
print( "Game over. Your secret number was:{}".format(guess))
break
else :
print("Sorry, I did not understand your input.")
here is the error :
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Thanks in advance.I'd really appreciate your help I'm stuck in this
A couple of things.
You should probably print the guess so that the user knows whether it is too high or too low
low==ans doesn't make any sense. ans will either be "h", "l", or "c", assuming the user follows the rules. low and high need to be numbers in order to generate the guess appropriately
Also your logic was incorrect. The below code works.
print("Please think of a number between 0 and 100!")
low = 0
high = 100
check = False
while True:
guess = (low + high)/2
print("My guess is: %i" % guess)
ans = input("Enter 'h' if guess it too high, 'l' if too low, or 'c' if correct: ")
print(ans)
if ans == "h":
high = guess
elif ans == "l":
low = guess
elif ans == "c":
print("Game over. Your secret number was:{}".format(guess))
break
else:
print("Sorry, I did not understand your input.")
On the line low = ans you set low to be a string value, the string value "h"
Then on the second time you pass through the loop, you try to calculate
(low + high)/2` You can't calculate ("h" + 100)/2 because you cant add the string to the integer. This is a "type error"
For each line explain to a friend (or a soft toy) what each line does and why you are certain each line is correct.

Python Guessing Game: Prevent Python guessing the same numbers

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

less than or more than by a certain amount

This game gets the user to guess a 4 digit number and gives feedback straight after the user guesses displaying 'Y' if the user gets the number right and displays 'H' if the guess is at most 3 higher than the number and obviously the opposite of displaying 'L' for at most 3 below the number. but this is my issue, i cant get it to display the 'H' and 'L' at 3 above or below! any help is appreciated.. code is below where i have attempted it.
from random import randint
guessesTaken = 0
randomNumber = [str(randint(1, 9)) for _ in range(4)] # create list of random nums
while guessesTaken < 10:
guesses = list(input("Guess Number: ")) # create list of four digits
check = "".join(["Y" if a==b else "H" if int(a)< 3 int(b) else "L" for a, b in zip(guesses,randomNumber)])
if check == guesses: # if check has four Y's we have a correct guess
print("Congratulations, you are correct, it took you", guessesTaken, "guesses.")
break
else:
guessesTaken += 1 # else increment guess count and ask again
print(check)
if guessesTaken == 10:
print("You lose")
Repaired that, see comments.
from random import randint
guessesTaken = 1 # repaired that. you cannot guess correctly on "0 guesses".
randomNumber = [str(randint(1, 9)) for _ in range(4)]
while guessesTaken < 10:
guesses = list(input("Guess Number: "))
#repaired check cases
check = "".join(["Y" if a == b else "L" if int(a) < int(b) and int(a)+3 >= int(b) else "H" if int(a) > int(b) and int(a)-3 <= int(b) else '?' for a, b in zip(guesses,randomNumber)])
if check == "YYYY": # repaired this check
print("Congratulations, you are correct, it took you", guessesTaken, "guesses.")
break
else:
guessesTaken += 1
print(check)
else: # loop is exhausted
print("You lose")
Guess Number: 4444
?HLH
Guess Number: 2262
?LYL
Guess Number: 7363
LYYY
Guess Number: 8363
LYYY
Guess Number: 9363
Congratulations, you are correct, it took you 5 guesses.
While it works, such a long list comprehension is a PITA to write and maintain.
Better keep your statements short and refactor common things out.

Guess the number game optimization (user creates number, computer guesses)

I am very new to programming so I decided to start with Python about 4 or 5 days ago. I came across a challenge that asked for me to create a "Guess the number" game. After completion, the "hard challenge" was to create a guess the number game that the user creates the number and the computer (AI) guesses.
So far I have come up with this and it works, but it could be better and I'll explain.
from random import randint
print ("In this program you will enter a number between 1 - 100."
"\nAfter the computer will try to guess your number!")
number = 0
while number < 1 or number >100:
number = int(input("\n\nEnter a number for the computer to guess: "))
if number > 100:
print ("Number must be lower than or equal to 100!")
if number < 1:
print ("Number must be greater than or equal to 1!")
guess = randint(1, 100)
print ("The computer takes a guess...", guess)
while guess != number:
if guess > number:
guess -= 1
guess = randint(1, guess)
else:
guess += 1
guess = randint(guess, 100)
print ("The computer takes a guess...", guess)
print ("The computer guessed", guess, "and it was correct!")
This is what happened on my last run:
Enter a number for the computer to guess: 78
The computer takes a guess... 74
The computer takes a guess... 89
The computer takes a guess... 55
The computer takes a guess... 78
The computer guessed 78 and it was correct!
Notice that it works, however when the computer guessed 74, it then guessed a higher number to 89. The number is too high so the computer guesses a lower number, however the number chosen was 55. Is there a way that I can have the computer guess a number that is lower than 89, but higher than 74? Would this require additional variables or more complex if, elif, else statements?
Thank you Ryan Haining
I used the code from your reply and altered it slightly so the guess is always random. If you see this, let me know if this is the best way to do so.
from random import randint
def computer_guess(num):
low = 1
high = 100
# This will make the computer's first guess random
guess = randint(1,100)
while guess != num:
print("The computer takes a guess...", guess)
if guess > num:
high = guess
elif guess < num:
low = guess + 1
# having the next guess be after the elif statement
# will allow for the random guess to take place
# instead of the first guess being 50 each time
# or whatever the outcome of your low+high division
guess = (low+high)//2
print("The computer guessed", guess, "and it was correct!")
def main():
num = int(input("Enter a number: "))
if num < 1 or num > 100:
print("Must be in range [1, 100]")
else:
computer_guess(num)
if __name__ == '__main__':
main()
what you are looking for is the classic binary search algorithm
def computer_guess(num):
low = 1
high = 100
guess = (low+high)//2
while guess != num:
guess = (low+high)//2
print("The computer takes a guess...", guess)
if guess > num:
high = guess
elif guess < num:
low = guess + 1
print("The computer guessed", guess, "and it was correct!")
def main():
num = int(input("Enter a number: "))
if num < 1 or num > 100:
print("Must be in range [1, 100]")
else:
computer_guess(num)
if __name__ == '__main__':
main()
The algorithm works by selecting a low and high limit to start with (in your case low=1 and high=100). It then checks the midpoint between them.
If the midpoint is less than number, the midpoint becomes the new lower bound. If the midpoint is higher, it becomes the new upper bound. After doing this a new midpoint is generated between the upper and lower bound.
To illustrate an example let's say you're looking for 82.
Here's a sample run
Enter a number: 82
The computer takes a guess... 50
The computer takes a guess... 75
The computer takes a guess... 88
The computer takes a guess... 82
The computer guessed 82 and it was correct!
So what's happening here in each step?
low = 1, high = 100 => guess = 50 50 < 82 so low = 51
low = 51, high = 100 => guess = 75 75 < 82 so low = 76
low = 76, high = 100 => guess = 88 88 > 82 so high = 88
low = 76, high = 88 => guess = 82 82 == 82 and we're done.
Note that the time complexity of this is O(lg(N))
I briefly made the game which you need with follows:
import random
guess=int(input("Choose a number you want the computer to guess from 1-100: "))
turns=0
a=None
compguess=random.randint(1,100)
while turns<10 and 100>guess>=1 and compguess!=guess: #computer has 10 turns to guess number, you can change it to what you want
print("The computer's guess is: ", compguess)
if compguess>guess:
a=compguess
compguess=random.randint(1,compguess)
elif compguess<guess:
compguess=random.randint(compguess,a)
turns+=1
if compguess==guess and turns<10:
print("The computer guessed your number of:" , guess)
turns+=1
elif turns>=10 and compguess!=guess:
print("The computer couldn't guess your number, well done.")
input("")
This is a bit rusty, but you could improve it by actually narrowing down the choices so the computer has a greater chance of guessing the right number. But where would the fun in that be? Notice how in my code, if the computer guesses a number which is greater than than the number the user has inputed, it will replace 100 from the randint function with that number. So if it guesses 70 and its too high, it won't choose a number greater than 70 after that. I hope this helps, just ask if you need any more info. And tell me if it's slightly glitchy
This is how I went about mine...
__author__ = 'Ghengis Yan'
print("\t This is the age of the computer")
print("\n The computer should impress us... the Man")
import random
#User chooses the number
the_number = int(input("Human Choose a number between 0 and 100 "))
tries = 1
computer = random.randint(0,100)
# User choose again loop
while the_number > 100:
the_number = int(input("I thought Humans are smarter than that... \nRetype the number... "))
if the_number <= 100:
print("Good")
# Guessing Loop
while computer != the_number:
if computer > the_number:
print(computer, "lower... Mr. Computer")
else:
print(computer, "higher... Mr. Computer")
computer = int(random.randint(0,100))
tries += 1
print("Computer Congratulations... You beat the human! The Number was ", the_number)
print("It only took a computer such as yourself", tries, "tries to guess it right... pathetic")
input("\nPress the enter key to exit.")
What I did for the same challenge was:
1) Define a variable that records the max value input by guessing computer.
Ex:
max_guess_number = 0
2) Define another variable with the lowest guessed value.
Ex.
min_guess_number = 0
3) Added in the "if computer_guess > secret_number" clause the following code (I added -1 so that the computer wouldn't try to guess the already previously tried number):
max_guess_number = guess - 1
computer_guess = random.randint(min_guess_number, max_guess_number)
4) Added the following code in the "if computer_guess < secret_number":
min_guess_number = guess + 1
computer_guess = random.randint(min_guess_number, max_guess_number)
Worth noting is the fact that I set my while loop to loop until another variable "guess_status" changes into a value 1 (the default I set to 0). This way I actually saw the result when the while loop finished.
print 'Please think of a number between 0 and 100!'
low = 0
high = 100
while(True):
rand = (high+low)/2
print 'Is your secret number '+str(rand)+'?'
ans = 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 ans=='h':
high = rand
elif ans=='l':
low = rand
elif ans=='c':
print "Game over. Your secret number was:",rand
break
else:
print "Sorry, I did not understand your input"
You only need two new variables to keep track of the low and high limits :
low = 1
high = 100
while guess != number:
if guess > number:
high = guess - 1
else:
low = guess + 1
guess = randint(low, high)
print ("The computer takes a guess...", guess)
Try this:
import random
player = int(input("tap any number: "))
comp = random.randint(1, 100)
print(comp)
comp_down = 1
comp_up = 100
raw_input("Press Enter to continue...")
while comp != player:
if comp > player:
comp_up = comp - 1
comp = random.randint(comp_down, comp_up)
print(comp)
if comp < player:
comp_down = comp + 1
comp = random.randint(comp_down, comp_up)
print(comp)
if comp == player:
break
If you use the stuff in the chapter (guessing this is from the Dawson book) you can do it like this.
import random
#program allows computer to guess my number
#initial values
user_input1=int(input("Enter number between 1 and 100: "))
tries=1
compguess=random.randint(1, 100)
#guessing loop
while compguess != user_input1:
if compguess > user_input1:
print("Lower Guess")
compguess=random.randint(1, 100)
print(compguess)
elif compguess < user_input1:
print("Higher Guess")
compguess=random.randint(1, 100)
print(compguess)
tries += 1 #to have program add up amount of tries it takes place it in the while block
print("Good job Computer! You guessed it! The number was,", user_input1, \
" and it only took you", tries, " tries!")
import random
corr_num = random.randint(1,100)
player_tries = 0
com_tries = 0
while player_tries <5 and com_tries < 5:
player = int(input("player guess is "))
if player > corr_num:
print("too high")
player_tries +=1
if player < corr_num:
print("too low")
player_tries +=1
if player == corr_num:
print("Player wins")
break
computer = random.randint(1,100)
print("computer guess is ", computer)
if computer > corr_num:
print("too high")
com_tries = 0
if computer < corr_num:
print("too low")
com_tries = 0
if computer == corr_num:
print ("computer wins")
break
else:
print("Game over, no winner")**strong text**
import random
x = 1
y = 99
hads = random.randint(x,y)
print (hads)
javab = input('user id: ')
while javab != 'd':
if javab == 'b':
x = hads
hads = random.randint(x,y)
print(hads)
javab = input('user id: ')
else:
javab == 'k'
y = hads
hads = random.randint(x,y)
print(hads)
javab = input('user id: ')
This is the code that I created to simplify the problem you were facing a lot more.
num = int(input("Enter a number between 1 and 100: "))
low = 1
high = 100
guess = (low+high)//2
while guess != num:
guess = (low+high)//2
print("The computer takes a guess...", guess)
if guess > num:
high = guess
else:
low = guess + 1
print("The computer guessed", guess, "and it was correct!")
import random
userNum = int(input("What will the secret number be (1-100)? "))
attempts = 0
guess = 0
lowCap = 1
highCap = 100
while guess != userNum:
guess = random.randint(lowCap,highCap)
if guess > userNum:
highCap = guess
attempts += 1
elif guess < userNum:
lowCap = guess
attempts += 1
print("The computer figured out the secret number in", + attempts, "tries.")
I was doing a similar scenario today for an assignment and only now figured out how to make it easily cut down through the numbers by changing random.randint(1, 100) to random.randint(lowCap, highCap) which will change as the computer keep making guesses.

Categories