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

时间:2015-02-23 09:57:31

标签: python python-2.7 loops while-loop break

我有一个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

3 个答案:

答案 0 :(得分:1)

您需要转换为int,raw_input会返回一个字符串,因此您要将stringint进行比较,而guess = int(raw_input("Give your age: ")) age == guess: ^^ ^^^ int str 永远不会评估为True:

in

不确定代码的其余部分是做什么的,但您可以使用while x not in {"yes","YES","no", "NO"}: 来替换&#39>:

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

哟在你的if语句中也不需要parens:

{{1}}

答案 1 :(得分:0)

每次循环时都必须定义中断条件。

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

请在while循环中添加guess,以便更改其值,您将达到中断状态。

答案 2 :(得分:-1)

最好改变无限迭代的条件。

# while guess != age:
while True: