【问题标题】:Repeat a for loop after user input?用户输入后重复for循环?
【发布时间】:2022-01-02 21:16:56
【问题描述】:

让我用一个例子来解释我的问题。

这里我有一个简单的 for 循环:

for x in range(10)
    print(x)

输出:0 1 2 3 4 5 6 7 8 9

现在,如果我从烧瓶网站或麦克风中获取用户输入,让人们说是或否,那么我希望它再次启动 for 循环或根据响应跳出 for 循环。如果对方说是,那么再次重做 for 循环,或者如果对方说没有,则退出 for 循环并继续执行其他代码。

问题:

如何在用户输入后重复一个 for 循环。

我正在询问如何使用 for 循环而不是 while 循环来执行此操作,因为我想将其放在执行其他操作的 while 循环中。

【问题讨论】:

  • 为什么不...将您想要重复的 for 循环,直到发生某些事情...放入 while 循环?您知道,您已经知道的东西,用于重复代码直到发生某些事情?你说你已经“想把它放在一个while循环中”......那么那个循环的条件是什么?那个while循环怎么还没有为你解决问题?基本上我不明白你实际上是如何在这里提出 question 的。看来您已经完全理解它的工作原理了。

标签: python for-loop user-input


【解决方案1】:

将你的循环放入另一个循环中:

while True:
    for x in range(10):
        print(x)
    if not input("Do it again? ").lower().startswith("y"):
        break

如果嵌套循环的数量开始变得笨拙(任何超过三级深度的东西开始难以阅读 IMO),请将其中的一些逻辑放入函数中:

def count_to_ten():
    for x in range(10):
        print(x)


while True:
    count_to_ten()
    if not input("Do it again? ").lower().startswith("y"):
        break

【讨论】:

    【解决方案2】:

    您还没有指定如何检索输入,所以我在下面的代码 sn-p 中省略了它:

    should_run_loop = True
    
    while should_run_loop:
        for x in range(10)
            print(x)
        should_run_loop = # code to retrieve input
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      • 2013-01-29
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      相关资源
      最近更新 更多