Python - 在循环结束时检查是否需要再次运行

3

这是一个非常基础的问题,但我现在想不到怎么做。我如何设置一个循环,每次运行函数时都会询问是否再次运行它。所以它运行后会说类似于;

"再次循环?y/n"

4个回答

14
while True:
    func()
    answer = raw_input( "Loop again? " )
    if answer != 'y':
        break

6
keepLooping = True
while keepLooping:
  # do stuff here

  # Prompt the user to continue
  q = raw_input("Keep looping? [yn]: ")
  if not q.startswith("y"):
    keepLooping = False

1
+1:正式的退出条件,没有使用break语句(此外,我还删除了多余的打印语句) - undefined
啊,谢谢S. Lott。我在赶时间,错过了那个问题 - 谢谢! :) - undefined

5

通常有两种方法,都已经提到了,它们分别是:

while True:
    do_stuff() # and eventually...
    break; # break out of the loop

或者

x = True
while x:
    do_stuff() # and eventually...
    x = False # set x to False to break the loop

两种方法都可以正常工作。从“声音设计”角度来看,最好使用第二种方法,因为:1)在某些语言的嵌套范围中,break可能具有反直觉的行为;2)第一种方法与“while”的预期使用相反;3)您的例程应始终具有单个退出点。


现在,如果你只保留这两段代码,并移除最后三个段落,我保证我会给你点赞 ;) - undefined
嗯,我已经更加直接了。只是出于好奇,我说的有什么问题吗?还是只是我的表达方式有问题? - undefined

1
While raw_input("loop again? y/n ") != 'n':
    do_stuff()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接