gpt4 book ai didi

Python 对分猜数游戏

转载 作者:行者123 更新时间:2023-11-28 21:09:41 25 4
gpt4 key购买 nike

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

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, or 如果它不是 h, or 如果它不是 l做这个。它不能同时是三个东西,所以它总是评估为真。

相反,您应该使用 if response not in ['c','h','l'],这基本上就像用 替换 or 在上面的句子中。或者在您的情况下更好,只需使用 else 语句,因为您现有的条件已经确保您要检查的内容。

关于Python 对分猜数游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37882643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com