当条件满足时,while 循环不会中断

While loop not breaking when condition met

我有一个 python 代码试图通过询问一些问题来猜测用户的年龄。 问题是,当用户的年龄等于变量时,while 循环不会中断。这是我的代码:

age = 50
guess = raw_input("Give your age: ")
while guess != age:
  print "Are you above ",age,"?"
  x = raw_input()
  while (x != "yes") and (x != "YES") and (x != "no") and (x != "NO"):
    print "Answer with yes/YES, no/NO"
    x = raw_input()
  if (x == "yes") or (x == "YES"):
    age = 2*age-age/2
  else:
    age = age/2

  if age == guess:
    break

print "Your age is ",age

您需要转换为 int、raw_input returns 一个字符串,这样您就可以将 stringint 进行比较,后者永远不会计算为正确:

guess = int(raw_input("Give your age: "))

age == guess:
^^      ^^^
int     str

也不确定其余代码在做什么,但您可以使用 in 替换 and 的:

while x not in  {"yes","YES","no", "NO"}:

你也不需要在你的 if 语句中使用括号:

if  x == "yes" or x == "YES":

每次循环都要定义中断条件

在您的代码中,您只定义了一次 guess。所以它的值不会改变。

请在while循环中加入guess,使其值发生变化,达到break条件。

最好把无限迭代的条件改一下

# while guess != age:
while True: