Basic Python code not Working - python

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

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 guess my number exercise marked wrong on edX

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.

Checking 2 int variables

I have 2 int variables. One contains user input, and the other is a computer generated number (0,99).
How can I check if the input variable contains a digit that is also in the computer generated numbers?
For a first example, if the user enters 45 and the computers guess was 54?
Or, if the user guesses one of the digits correctly, like, the user guesses 23, and the computer guess is 35?
Guess = int(input("Please guess a number between 0 to 99:"))
if Guess <= 99 and Guess >= 0:
break
except ValueError:
print("")
RandomNum = random.randint(0,99)
print("Random Generated Number",RandomNum)
if RandomNum == Guess:
print("Jackpot!! You win 100 !")
if RandomNum == Guess[0,1]:
print("Right Digits,wrong order. You win 10")
It appears that you want to check if the user's number contains the same digit as the computer-generated numbers.
If you only ever going to have two digits numbers you can get away with if str(RandomNum) == str(Guess)[::-1]:. This will check if the string value of RandomNum is equal to the string value of Guess in reverse.
If you want a more generalized solution then first you will need to define the desired behavior.

Python returning untrue values?

I'm a newbie to Python, and I was working on a number guessing game in Python. However, when I set up the parameters:
import random
numberchosen = random.randint(0,100)
numberchosenstr = str(numberchosen)
print ("Let's play a number game")
numberguessed = input("Guess a number ")
print ("You guessed " + numberguessed)
if numberguessed > '100':
print ("You guessed too high, choose a number below 100")
if numberguessed < '0':
print ("You guessed too low, choose a number above 0")
if numberguessed != numberchosen:
print ("wrong")
But, when I run the module, and choose the number 5 for instance, or any number that is within the correct range yet not the correct number, it always returns
Let's play a number game
Guess a number 5
You guessed 5
You guessed too high, choose a number below 100
wrong
So, my question is, why does Python return the >100 error, and what are some ways to fix it?
You're comparing strings, which is done lexicographically (i.e. alphabetically, one character at a time). But even if one were an int, strings are always greater than numbers. You need to take the quotes off your comparison number, and call int() on your input, like so:
numberguessed = int(input("Guess a number ")) # convert to int
print ("You guessed {}".format(numberguessed)) # changed this too, since it would error
if numberguessed > 100: # removed quotes
print ("You guessed too high, choose a number below 100")
if numberguessed < 0: # removed quotes
print ("You guessed too low, choose a number above 0")

How to code a reverse 'Guess my Number' game in python?

I've written a game where a player tries to guess a random number (see code below). Suggestions such as 'Too low...' and 'Too High...' are also provided. But what about reversing it and letting the computer guess a number that a player has selected. I have difficulty with this and I dont know why. I think I need a 'push' from someone but not the actual code as I need to attempt this myself. I would appreciate it if some would help me on this.
Here is the code(Python 3) where the player has to guess the number:
#Guess my Number - Exercise 3
#Limited to 5 guesses
import random
attempts = 1
secret_number = random.randint(1,100)
isCorrect = False
guess = int(input("Take a guess: "))
while secret_number != guess and attempts < 6:
if guess < secret_number:
print("Higher...")
elif guess > secret_number:
print("Lower...")
guess = int(input("Take a guess: "))
attempts += 1
if attempts == 6:
print("\nSorry you reached the maximum number of tries")
print("The secret number was ",secret_number)
else:
print("\nYou guessed it! The number was " ,secret_number)
print("You guessed it in ", attempts,"attempts")
input("\n\n Press the enter key to exit")
Thanks for your help.
at each iteration through your loop, you'll need a new random.randint(low,high). low and high can be figured out by collecting your computers guesses into 2 lists (low_list) and (high_list) based how the user responds when the computer tells the user it's guess. Then you get low by max(low_list)+1 and you get high by min(high_list)-1. Of course, you'll have to initialize low_list and high_list with the lowest and highest numbers allowed.
You could just keep the lowest of the "too high" guesses and the highest of the "too_low" guesses instead of the lists. It would be slightly more efficient and probably the same amount of work to code, but then you couldn't look back at the computer's guesses for fun :).
You begin with a range from the minimum allowed number to the maximum allowed number, because the unknown number could be anywhere in the range.
At each step, you need to choose a number to query, so dividing the space into two blocks; those on the wrong side of your query number will be dropped. The most efficient way to do this in the minimum number of queries is to bisect the space each time.
I suggest you restrict the game to integers, otherwise you'll end up with a lot of messing about with floating point values regarding tolerance and precision and so on.
Assuming you know the range of numbers it could be is (a,b).
Think about how you would narrow down the range. You'd start by guessing in the middle. If your guess was low, you'd guess between your last guess and the top value. If it was high you'd guess between the lowest possible value and the last guess. By iteratively narrowing the range, eventually you'd find the number.
Here's some pseudo code for this:
loop{
guess = (a+b)/2
if high:
b = guess - 1
else if low:
a = guess + 1
else:
guess = answer
}
I just did this with a different person, use a while loop and use print("<,>,="), then do an if statement. You need a max point, middlepoint and low point and to get the middle point you need to do midpoint=((highpoint=lowpoint)//2) and in the if statement you have to do change the maxpoint and lowpoint.

Categories