Mitchell Clark Mitchell Clark - 2 months ago 17
Python Question

Automatic Bisectional number game for Python

I have been working on a Bisectional Number guessing game and I would like to make it work automatically, but the code appears to be getting stuck in a loop.

Any suggestions?

x = 75

low = 0
high = 100

guessing = True

while guessing:

guess = int((high + low) // 2)

if guess == x:
guessing = False
elif guess < x:
high = guess
else:
low = guess

print("Your number is ", str(guess))

Answer

I think it will work:

x = 75
low = 0
high = 100
guessing = True
while guessing:
    guess = (high + low) // 2
    print("guess:",guess)
    if guess == x:
        guessing = False
    elif guess < x:
        low = guess
    else:
        high = guess
print("Your number is ", guess) 

output:

guess: 50
guess: 75
Your number is  75

You don't need to explicitly convert it to int because you are using integer division here guess = int((high + low) // 2) And reverse the elif ..else logic..

Hope this will help you.