如何在python中结束我的while循环

时间:2013-10-29 20:42:29

标签: python loops while-loop

我正在尝试为自己创建一个猜谜游戏。我想让计算机有一个随机数,我必须猜测。基于我的猜测,它会以“更高或更低”的方式响应,这应该在我得到正确的数字之前继续发生但是现在发生的是现在当我猜测时,它说更高或更低并且只是重复这个整个页面。我如何结束这个循环,并确保在每个“更高”或“更低”之后,我只是得到另一个变化。请在下面找到代码。

import random 
the_number = random.randrange(100)+ 1
guess= int(raw_input("Take a guess:  "))
tries = 1
while (guess != the_number):
   if (guess > the_number):
      print "Lower..."
      break
   elif (guess<the_number):
      print " Higher..."
      break

   elif (guess == the_number):
      print "Awesome achievement"
      break
   else:
      print "Better luck next time."
      guess = int(raw_input("Take another guess  "))

2 个答案:

答案 0 :(得分:2)

import random

the_number = random.randrange(100) + 1
tries = 0
while True:
  tries += 1
  guess = int(raw_input("Take a guess:  "))
  if guess > the_number:
    print "Lower..."
  elif guess < the_number:
    print " Higher..."
  else:
    print "Awesome achievement, it took you", tries, "tries"
    break

答案 1 :(得分:0)

类似这样的事情

import random
def main():
    secret = random.randint(1, 10)
    while (guess != secret):
    guess = int(raw_input("Guess a number between 1 and 10: "))
        if guess > secret:
        print "too high."
        elif guess < secret:
            print "too low."
        elif guess <1 or guess > 10:
            print "invalid guess."
        elif guess == secret:
            print "You win"
            break