【问题标题】:Looping a program with "while" statement使用“while”语句循环程序
【发布时间】:2016-06-26 13:46:47
【问题描述】:

所以,我有这个程序,你必须在其中猜一个数字,我已经对其进行了编码,以便程序会告诉你你猜的数字是高于还是低于真实数字。我的问题是程序在告诉用户猜测更高或更低之后结束。我希望程序循环,这样程序在猜到我预设的数字之前不会结束。这是我的代码:

    number = 10
    guess = int(input("Type in an integer: "))
    if guess == number:
        print ("Good Job!")
    elif guess < number:
        print ("The number is higher")
    else:
        print ("The number is lower")
    while guess!= number:
        print ("Try Again")
    print ("Done") 

我尝试使用 while 循环来循环程序,直到正确猜到数字,但是“再试一次”脚本永远循环...感谢您的帮助!

【问题讨论】:

    标签: python loops while-loop


    【解决方案1】:

    您的流控制设计不正确,但您可以通过将代码包装在while 循环中并应用break 一次guess == number 来修复。 guess!=number 的其他情况,循环只是继续运行:

    number = 10
    while True:
        guess = int(input("Type in an integer: "))
        if guess == number:
            print ("Good Job!")
            break
        elif guess < number:
            print ("The number is higher")
        else:
            print ("The number is lower")
    print ("Done")
    

    您可以在 python here 中阅读有关 while 循环的更多信息

    【讨论】:

      【解决方案2】:

      while 循环不能那样工作。看起来您期待某种goto,它会猜测您希望它重复什么,但它会重复的只是块的内容。当它到达while guess != number:,这是真的,它会打印那个短语,然后检查guess是否不等于number,这仍然是真的,因为它永远没有改变。

      将需要重复的所有内容放入循环中:

      number = 10
      guess = int(input("Type in an integer: "))
      while guess != number:
          if guess < number:
              print ("The number is higher")
          else:
              print ("The number is lower")
          guess = int(input("Type in an integer: "))
      print ("Good Job!")
      print ("Done") 
      

      【讨论】:

        【解决方案3】:

        尝试以下方法:

        number = 10
        guess = 9
        while guess!= number:
            guess = int(input("Type in an integer: "))
            if guess == number:
                print ("Good Job!")
            elif guess < number:
                print ("The number is higher")
            elif guess > number:
                print ("The number is lower")
            else:
                print ("Try Again")
        print ("Done") 
        

        【讨论】:

        • 带有解释的答案更相关。 !
        猜你喜欢
        • 1970-01-01
        • 2015-05-19
        • 1970-01-01
        • 1970-01-01
        • 2013-10-21
        • 2017-05-02
        • 2015-07-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多