【问题标题】:While loop in python allowing only one of two responsesPython中的while循环仅允许两个响应之一
【发布时间】:2017-10-28 06:33:33
【问题描述】:

我有一个 while 循环,我想限制两个答案之一。一个会继续循环,另一个会打破它。问题是代码类似于以下内容:

choice = "y"
while choice == "y":
    if condition:
        print ("something")
    choice = input("continue?")

我只想允许 y 或 n 个答案,其他所有答案都应该再次提示。请帮忙。我发现有几件事很接​​近,但是当我尝试时,我得到了一个无限循环的提示。

【问题讨论】:

  • 老实说,这看起来更像是请人做作业。如果这是一个诚实的问题,您可能需要检查 Python 教程中的关键字“break”和“if/else”语句。
  • 如果是家庭作业,我会请老师帮助我。但我正在自学 Python。我只是碰巧遇到了一个部分,我被卡住了,无法解决我想做的事情,没有帮助。

标签: python loops while-loop


【解决方案1】:

您可以使用while True。循环不会停止,直到它收到用户输入的“Y”或“N”。试试这个:

while True:
        choice = input('continue?')
        if choice =='Y' or choice =='N':
            print(choice )
            break
        else:
            continue

【讨论】:

  • 也许我应该更清楚一点。如果用户回答 Y,那么我希望它再次运行代码(它说打印一些东西)。如果用户回答 N,我希望它结束​​程序。所有其他响应都应导致提示重复,直到给出有效条目。
【解决方案2】:

我认为您正在寻找sentinel controlled program。循环将一直询问,直到您输入标志值“否”。

while (c != 'no'):
    ...     c = input("continue?")
    ...     if 2 > 1:
    ...             print('It is')

【讨论】:

    【解决方案3】:

    试试这个。它接受yes/Yes/YES/Y/y/No/NO/no/n/N

    valid=['Y','N']
    while True:
            choice = str(raw_input('continue?'))
            if choice.upper()[0] in valid:
                print(choice)
                print ("Write your code here")
                break
            else:
                continue
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-08
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 2012-10-30
      • 2014-11-02
      • 2017-11-09
      相关资源
      最近更新 更多