[英]Repeat a for loop after user input?
让我用一个例子来解释我的问题。
这里我有一个简单的 for 循环:
for x in range(10)
print(x)
output: 0 1 2 3 4 5 6 7 8 9
现在,如果我从 flask 网站或麦克风中获取用户输入,让人们说是或否,那么我希望它再次启动 for 循环或根据响应跳出 for 循环。 如果该人说是,则再次重做 for 循环,或者如果该人说没有,则退出 for 循环并继续执行其他代码。
问题:
如何在用户输入后重复 for 循环。
我在问如何使用 for 循环而不是 while 循环来执行此操作,因为我想将它放在执行其他操作的 while 循环中。
您尚未指定如何检索输入,因此我在以下代码片段中省略了该内容:
should_run_loop = True
while should_run_loop:
for x in range(10)
print(x)
should_run_loop = # code to retrieve input
将您的循环放入另一个循环中:
while True:
for x in range(10):
print(x)
if not input("Do it again? ").lower().startswith("y"):
break
如果嵌套循环的数量开始变得难以处理,请将其中的一些放在 function 中:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.