高低:计算机猜测你的号码

时间:2015-06-07 04:47:05

标签: python

所有。我对编程很陌生,而且我试图弄清楚为什么我的代码没有正常工作。它运行正常,直到你告诉计算机它的第一个猜测是否太高(h)或太低(l)。如果,例如,猜测太高,并告诉计算机,每次猜测后将继续猜测更低,无论你输入是否太低(l)。它反过来也是相反的。希望有人可以提供帮助。这是代码!

import random
import time

print "Think of a number between 1 and 100 and I'll try and guess it."
time.sleep(2)
print "Let me know if my guess is too (h)igh, too (l)ow, or (c)orrect."
time.sleep(2)

guess = int(raw_input("Pick your number between 1-100: "))

low = 1
high = 100
tries = 0
compguess = random.randrange(low, high)
h = compguess > guess
l = compguess < guess
c = compguess == guess

while compguess != guess:
    tries += 1
    print "Is it", compguess

if h:
    raw_input ()
    new_high = (compguess - 1)
    compguess = random.randint(low, new_high)

elif l:
    raw_input ()
    new_low = (compguess + 1)
    compguess = random.randint(new_low, high)

elif c:
    raw_input ()
    print("The computer guessed your number of: ", guess)

原谅间距。我不太确定如何正确复制它。

1 个答案:

答案 0 :(得分:2)

raw_input()函数返回一个值。如果您没有将返回值赋给变量或以其他方式对其执行某些操作,则返回的值将被Python丢弃。

您可能需要以下内容:

print "Is it", compguess
answer = raw_input()
if answer == "h":
    ...
elif answer == "l":
    ...

这样,您提示用户输入,等待用户输入内容,然后根据用户输入的内容进行操作。

您也不需要hlc局部变量。它们实际上并不代表您的代码。

最后,为什么要求用户告诉计算机用户在想什么号码?这个练习的重点不是让计算机猜测用户的号码,而不知道结果是什么?