【问题标题】:While Loop Guessing Number Game - PythonWhile循环猜数游戏 - Python
【发布时间】:2014-10-30 06:42:34
【问题描述】:

我正在尝试制作一个“猜测 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"

【问题讨论】:

  • 您不会在循环内更改guess...

标签: python loops while-loop jython


【解决方案1】:

如果将input 语句移到while 循环中,应该没问题。

【讨论】:

    【解决方案2】:

    你忘了在循环内猜测

      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!"
    

    【讨论】:

    • 使用此代码,第一次猜测将不会被评估!
    • @user3015703,我只为循环指定修改。但是在调用循环之前输入了guess,因此应该对其进行评估
    【解决方案3】:

    使用这个:

    import random
    
    def numberGuess():
      print("I'm thinking of a number between 1 and 10")
      randNum = random.randrange(1,11) # this line generates a random number
      while guess != randNum:
        guess = int(input("Try to guess the number:")) # ask user for a number
        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"
    
    numberGuess()
    

    【讨论】:

      【解决方案4】:
      import random
      
      def numberGuess():
        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 True:
          if (guess == randNum):
              print ("You got it!")
              break
          if (guess > randNum):
              print ("Wrong! You guessed too high")
              guess = int(input("Try to guess the number:"))  # ask user for a number
          if (guess < randNum):
              print ("Wrong! You guessed too low")
              guess = int(input("Try to guess the number:"))  # ask user for a number
      
      numberGuess()
      

      【讨论】:

        猜你喜欢
        • 2021-04-29
        • 1970-01-01
        • 1970-01-01
        • 2021-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 2015-10-22
        相关资源
        最近更新 更多