繁体   English   中英

Python二等分数字猜谜游戏

[英]Python Bisection Number Guessing Game

我正在尝试编写一个简单的二等分方法问题,只要我没有注释掉的条件语句,它就可以很好地工作。 这是什么原因呢? 这不是作业问题。

low = 0 
high = 100 
ans = (low+high)/2 
print "Please think of a number between 0 and 100!"
print "Is your secret number " + str(ans) + "?"
response = 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. ") 
response = str(response)
while response != "c": 
   if response == "h":
        high = ans 
        ans = (low + high)/2 
        print "Is your secret number " + str(ans) + "?"
        response = 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. ")  
        response = str(response) 

   if response == "l": 
        low = ans 
        ans = (low + high)/2 
        print "Is your secret number " + str(ans) + "?"
        response = 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. ")  
        response = str(response)

   if response == "c" :
        break

  # if response != "c" or response != "h" or response != "l":
   #     response = raw_input("Please enter a 'h', 'l', or 'c' ")
    #    response = str(response)

print "Game over. Your secret number was: " + str(ans)

这是因为while循环与while循环具有相同的条件吗? 如果是这样,改变这一状况的最佳方法是什么?

该条件将永远是正确的,因为您正在将不平等与多个事物进行比较。 这就像问“如果此字符不是c还是不是h还是不是l请执行此操作 。一次不能是三件事,因此它将始终评估为true 。

相反,您应该if response not in ['c','h','l']使用if response not in ['c','h','l'] ,这基本上就像在上面的句子中替换or或 with 甚至对您而言更好,只需使用else语句,因为您的现有条件已经可以确保您尝试检查的内容。

我建议您使用double while循环:

while True:
    response = None
    print "Is your secret number " + str(ans) + "?"
    response = str(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."))

    while response not in ['h', 'c', 'l']:
        response = str(raw_input("Please enter a 'h', 'l', or 'c' "))

    if response == 'c':
         break

    if response == 'l':
        low = ans 
    else:
        high = ans 
    ans = (low + high)/2 

暂无
暂无

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

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