Reputation: 79
I write a code in python 3 which includes a binary serach alghorithm for finding a number. The user will enter 0,1 or 2 for higher or lower point. So, I use this code:
def guess():
i = 0
# i is the lowest number in range of possible guess
j = 100
# j is the highest number in range of possible guesses
m = 50
# m is the middle number in range of possible guesses
counter = 1
# counter is the number of guesses take.
print ("Please guess a number")
condition = input("Is your guess " + str(m) + "? (0 means it's
too low, 1 means it's your guess and 2 means it's too high) ")
while condition != 1:
counter += 1
if condition == 0:
i = m + 1
elif condition == 2:
j = m - 1
m = (i + j)//2
condition = input("Is your guess " + str(m) + "? (0 means
it's too low, 1 means it's your guess and 2 means it's too
high) ")
print ("It took" , counter , "times to guess your number")
guess()
Okay, after I run the output looks like:
Please guess a number
Is your guess 50? (0 means it's too low, 1 means it's your guess and 2 means
it's too high) 0
And when I enter 0
Is your guess 50.0? (0 means it's too low, 1 means it's your guess and 2
means it's too high)
It keeps giving 50.0 for the result but it should give me lower then 50. Is there any way for taking lower number from the program. Thank you!
Upvotes: 0
Views: 77
Reputation: 636
You need to cast your input to an integer, it is reading the input as a string.
condition = int(input("Is your guess " + str(m) + "? (0 means it's
too low, 1 means it's your guess and 2 means it's too high) ").strip())
By strip
, it will take care of removing whitespaces and newlines before converting the string into an integer.
Upvotes: 4
Reputation: 551
In Python 3, input()
will always return a string. Therefore, comparisons like condition == 0
or condition == 2
will always return false.
Instead, try checking for condition == '0'
or condition == '2'
. More generally, you should probably consider that users may input something other than 0, 1, or 2 and display an error message. That would have helped you catch this bug!
Upvotes: 2