简体   繁体   English

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

[英]High Low: Computer guesses your number

all. 所有。 I'm quite new to programming, and I'm trying to figure out why my code isn't working properly. 我对编程很陌生,并且试图弄清楚为什么我的代码无法正常工作。 It runs fine up until you tell the computer whether or not its first guess is too high (h), or too low (l). 它会正常运行,直到您告诉计算机它的第一个猜测是否太高(h)或太低(l)。 If, say, the guess is too high, and tell the computer that, each guess after will continue guessing lower, regardless of whether or not you enter too low (l). 例如,如果猜测值太高,并告诉计算机,则无论您输入的值是否太低(l),每次猜测之后都将继续猜测值较低。 It happens the other way around as well. 反之亦然。 Hopefully someone can help. 希望有人可以提供帮助。 Here's the code! 这是代码!

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)

Forgive the spacing. 原谅间隔。 I'm not quite sure how to copy it properly. 我不太确定如何正确复制它。

The raw_input() function returns a value. raw_input()函数返回一个值。 If you don't assign the return value to a variable or otherwise do something with it, the value returned is simply discarded by Python. 如果您不将返回值分配给变量或以其他方式对其进行处理,则返回的值将被Python丢弃。

You probably want something like: 您可能想要类似的东西:

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

That way, you prompt the user for input, wait for the user to type something, then act upon what the user typed. 这样,您提示用户输入,等待用户键入内容,然后对用户键入的内容进行操作。

You also don't need the h , l , or c local variables. 您也不需要hlc局部变量。 They don't actually serve a purpose in your code. 它们实际上在您的代码中没有作用。

Finally, why do you ask the user to tell the computer what number the user is thinking of? 最后,为什么要要求用户告诉计算机用户在想什么号码? Isn't the point of this exercise to get the computer to guess the user's number, without knowing what the result is? 这个练习的目的不是让计算机猜测用户的号码而不知道结果是什么吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM