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'):
Related
I need help with an assignment I have for Intro to Python.
The assignment is to have the computer pick a random number between 1 and 100 and the user has to guess the number. If your guess is too high then you will be told. If your guess was too low then you will be told. It will continue repeating until you guess the correct number that was generated.
My issue is that if an input is a string then you would get a prompt saying that it is not a possible answer. How do I fix this issue?
P.S. If it would not be too much trouble, I would like to get tips on how to fix my code and not an answer.
Code:
import random
#answer= a
a= random.randint(1,100)
#x= original variable of a
x= a
correct= False
print("I'm thinking of anumber between 1 and 100, try to guess it.")
#guess= g
while not correct:
g= input("Please enter a number between 1 and 100: ", )
if g == "x":
print("Sorry, but \"" + g + "\" is not a number between 1 and 100.")
elif int(g) < x:
print("your guess was too low, try again.")
elif int(g) > x:
print("your guess was too high, try again.")
else:
print("Congratulations, you guessed the number!")
So if you want to sanitize the input to make sure only numbers are being inputted you can use the isdigit() method to check for that. For example:
g=input("blah blah blah input here: ")
if g.isdigit():
# now you can do your too high too low conditionals
else:
print("Your input was not a number!")
You can learn more in this StackOverflow thread.
The program works as follows: you (the user) thinks of an integer between 0 (inclusive) and 100 (not inclusive). The computer makes guesses, and you give it input - is its guess too high or too low? Using bisection search, the computer will guess the user's secret number!
My code:
guess number using bisection
Ask for an input of number from the user
high = 100
low = 0
correct = False
response = ""
user_number = input("Please think of a number between 0 and 100!")
while (response != "c"):
guess = int((high + low)/2)
print("Is your secret number", guess, "?")
response = 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 not (response == "h" or response == "c" or response == "l"):
print("Sorry, I did not understand your input.")
elif (response is "h"):
high = guess
elif (response is "l"):
low = guess
print ("Game over. Your secret number was:", guess)
Currently the EdX website is marking my answer as incorrect, I checked the out put by trying input numbers such as 83, 8,42 it came out correctly as the edX website code's showing. Can someone give me some suggestions on where my code is flawed? Thank you.
I am newbie to Python.
Here is my Code that implements binary search to find the guessed number .I cant figure it out correctly how to make my code work.
Any help would be appreciated. Thanks.
print"Please think of a number between 0 and 100!"
guessed=False
while not guessed:
lo=0
hi=100
mid=(lo+hi)/2
print'Is you Secret Number'+str(mid)+'?'
print"Enter 'h' to indicate the guess is too high.",
print"Enter'l' to indicate the guess is too low",
print"Enter'c'to indicate I guessed correctly"
x=raw_input()
if(x=='c'):
guessed=True
elif(x=='h'):
#Too High Guess
lo=mid+1
elif(x=='l'):
lo=mid-1
else:
print("Sorry, I did not understand your input.")
print'Game Over','Your Secret Number was'+str()
Following points need to apply code:
Define lower and upper limit outside of for loop becsue if we define inside while loop, every time lo and hi variable will create with 0 and 100 value respectively.
Give variable name according to variable work.
lower = 0
higher = 100
God practice to Write function to wrap your code.
As guess number is higher then set Max Number to guess number.
As guess number is lower then set Min Number to guess number.
Demo:
import time
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 guessGame():
"""
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)
time.sleep(2)
while True:
mid = (min_no+max_no)/2
print'Is you Secret Number'+str(mid)+'?'
print"Enter 'h' to indicate the guess is too high.",
print"Enter'l' to indicate the guess is too low",
print"Enter'c'to indicate I guessed correctly"
x=raw_input().lower()
if(x=='c'):
print'Game Over','Your Secret Number was'+str(mid)
break
elif(x=='h'):
#- As guess number is higher then set max number to guess number.
max_no=mid - 1
elif(x=='l'):
#- As guess number is lower then set min number to guess number.
min_no = mid + 1
else:
print("Sorry, I did not understand your input.")
guessGame()
Output:
vivek#vivek:~/Desktop/stackoverflow$ python guess_game.py
Please input the low number range:1
Please input the high number range:100
Guess any number between 1 and 100.
Is you Secret Number50?
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 you Secret Number25?
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 you Secret Number12?
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 you Secret Number18?
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 you Secret Number15?
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 you Secret Number16?
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 you Secret Number17?
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 was17
I'm writing a program that is supposed to guess the user's secret number using bisection search. I feel like I understand the concept of bisection search quite well but my IDE (Canopy) won't let me 'run' the code, which I assume is due to an error or something that it wants me to do before I run it.
lowend = 1
highend = 100
guess = 50
choice = 0
print "Please think of a number between 0 and 100!"
while choice != 'c':
print "Is your secret number " + str(guess) + "?"
print "Enter 'h' to indicate the guess is too high.",
print "Enter 'l' to indicate the guess is too low.",
choice = raw_input("Enter 'c' to indicate I guessed correctly.")
if choice == 'c':
break
elif choice == 'h':
highend = guess
guess = (highend + lowend)/2
print 'Is your secret number ' + str(guess) + "?"
choice = 0
elif choice == 'l':
lowend = guess + 1
guess = (highend + lowend)/2
print 'Is your secret number ' + str(guess) + "?"
else:
print "Sorry, I did not understand your input."
choice = 0
print 'Your number is: ' + str(guess) + "."
I'm not sure if there's something I'm doing wrong, but Canopy's green 'run' button is greyed out. Why does this happen? Does anyone see anything obviously wrong with my code?
Did you get this yet?
I think your initial choice should be a space: choice = " "
Also you need parenthesis on your print statements.
Maybe you don't need the raw_ for your input?
Maybe some rounding or making your answers integers.
I guess u need to ask for an input with the raw_input function insted of just printin' those messages, the programm can't find l,h or c to make the comparissons.
Restart Canopy's IDE to solve your problem.
I faced similar problem when the other script went into an infinite loop.
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']: