【发布时间】:2014-05-04 01:43:10
【问题描述】:
我无法弄清楚我的代码有什么问题。我试图让用户想到一个介于 1 到 100 之间的数字,然后这个程序将能够猜到它。该程序将范围的高数和低数相加并除以二并将其用作猜测。如果程序猜测的数字高于他们的数字,则用户输入 1,如果低于他们的数字,则输入 -1,如果猜测正确,则输入 0。最多猜 7 次后,猜中的数字应该是对的。当我运行我的代码时,它会不断地将猜测打印为 50,并且永远不会改变。它似乎永远不会通过 if 语句。它应该在程序中运行并找到新的猜测。
def main():
import random
print("Guessing Game")
print("")
print("Think of a number 1 and 100 inclusive.\nAnd I will guess what it is in 7 tries or less.")
print("")
ready = input("Are you ready? (y/n): ")
print("")
if ready != "y" and ready != "n":
ready = input("Are you ready? (y/n): ")
if ready == "n":
print("Bye")
if ready == "y":
lo = 0
hi = 100
guess_high = 1
guess_same = 0
guess_low = -1
a = random.randint(1,100)
num_list = []
for i in range(1,100):
num_list.append(i)
while (lo <= hi):
guess_count = 0
for guess_count in range(1,8):
guess_count += 1
guess = (lo + hi) // 2
print("Guess",guess_count," : The number you thought was",guess)
user_response = input("Enter 1 if my guess was high, -1 if low, and 0 if correct: ")
if (user_response == 1):
hi = guess - 1
guess_count += 1
guess = (lo + hi) // 2
elif (user_response == -1):
lo = guess + 1
guess_count += 1
guess = (lo + hi) // 2
elif (user_response == 0):
print("Thank you for playing the Guessing Game.")
main()
【问题讨论】:
标签: python