-2

I currently have a code which is used to make the computer guess the number in my head. I keep getting an error because I am using a variable multiple times in one line.

import random

N = int(input())

Low = 0
High = N

p=False

guess = random.randint(Low, High)
print(guess)

def get_response():
    response = input()
    global p
    if response == 'l':
        high = guess - 1
        guess = random.randint(Low, high)
        print(guess)

    elif response == 'h':
        low = guess + 1
        guess = random.randint(low, High)
        print(guess)

    elif response == 'c':
        print("He got it")
        p=True

How could I solve this problem and how could I loop this? Thank you in advance!

2
  • 2
    That code shouldn't cause the error you're getting; you never even use the variable usedrandomnumber in the example despite that being the cause.
    – Aurora0001
    Nov 9, 2016 at 19:07
  • 2
    That error message tells you what's wrong: you tried to use that variable before you gave it a value. Since the code you posted doesn't illustrate the problem, we can't help you.
    – Prune
    Nov 9, 2016 at 19:08

1 Answer 1

0

you do not call the function it will do nothing

p dose not need to be global as there is no local to shadow it

also p looks like a flag to stop iterating but this is not needed as a break

statement can stop a while(True)

there is no usedrandomnumber and so no UnboundLocalError

print('think of a integer in the range [0,100]')
low, high = 0, 100
while(True):
    guess = (low + high)//2 # // int div
    cmd = input('is it %d [Yes(y), higher(h), lower(l)]\n>>> ' % guess)
    if cmd[0].lower()=='y':
        break
    elif cmd[0].lower()=='l':
        high = guess - 1
    elif cmd[0].lower()=='h':
        low = guess + 1
    else:
        print('please answer with "y", "h", or "l" ')
print("I win! your number is %d"%guess)

in short you need a loop to look for the number

prints to give instructions

input to get the command form the user cmd[0] will get the first letter of the command to distinguish them .lower() will lowercase to the commands are not case sensitive

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.