我写了一些代码来确定一个0到100之间的秘密号码。用户告诉机器猜测的数字(范围的一半)要么太高,要么太低,要么刚好。根据输入,机器使用对分搜索来调整猜测。当猜测正确时,用户按c键游戏结束。问题是,尽管“i didn't understand input”分支中存在条件,但当用户按下c(有效条目)时,该分支会触发,而这不是第一个猜测。你知道吗
例如,这里是输出-
Please think of a number between 0 and 100!
Is your secret number 50?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
Is your secret number 75?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. c
Sorry, I did not understand your input.
Game over. Your secret number was:75
>>>
这里的代码是strong
High=100
Low=0
Guess=50
user_input=0
print('Please think of a number between 0 and 100!')
while user_input != 'c':
print("Is your secret number"+" "+str(Guess)+"?")
userinput = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
if user_input == 'h':
High=Guess
Guess= ((High+Low)/2)
if user_input == 'l':
Low=Guess
Guess= ((High+Low)/2)
if user_input != 'h' or 'l' or 'c':
print('Sorry, I did not understand your input.')
print ('Game over. Your secret number was:'''+ str(Guess))
提前谢谢。我已经为此绞尽脑汁好几个小时了。。。。你知道吗
试试这个而不是那个条件。你知道吗
您可能不必检查
user_input
是h
还是l
,因为第一对if
应该处理这个问题。你知道吗条件句不是这样的。你需要这样的东西:
或:
你目前的做法被理解为
由于
l
和c
是truthy,所以该分支将始终执行。你知道吗您还可以考虑使用
elif
,因此您的条件如下:除了
if
之外,您的逻辑还有一些错误。我推荐这样的:相关问题 更多 >
编程相关推荐