While 循环猜数游戏 - Python

新手上路,请多包涵

我正在尝试制作“猜 1-10 之间的数字”游戏,但 while 循环似乎一直在运行。我想编程让用户猜测一个数字然后显示它是否太高或太低等然后自动重新开始(循环)以允许用户再次选择。这段代码让它永远运行。你们能帮帮我吗?

 import random

def numberGuess():
  printNow("I'm thinking of a number between 1 and 10")
  guess = 0 # give guess a starting value
  randNum = random.randrange(1,11) # this line generates a random number
  guess = int(input("Try to guess the number:")) # ask user for a number
  print randNum
  while guess != randNum:
    if (guess == randNum):
      print "You got it!"
    if (guess > randNum):
      print "Wrong! You guessed too high"
    if (guess < randNum):
      print "Wrong! You guessed too low"

原文由 james 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 822
1 个回答

你忘了在循环中猜测

  while guess != randNum:
    guess = int(input("Try to guess the number:"))
    if (guess > randNum):
      print "Wrong! You guessed too high"
    if (guess < randNum):
      print "Wrong! You guessed too low"
  print "You got it!"

原文由 Ashoka Lella 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题