python - 如果需要再次运行,请检查循环结束

use*_*061 2 python loops

这是一个非常基本的问题,但我不能在第二个问题上思考.我如何设置一个循环,每当内部函数运行时询问是否再次执行它.所以它运行它然后说类似的东西;

"再次循环?y/n"

Mar*_*ote 13

while True:
    func()
    answer = raw_input( "Loop again? " )
    if answer != 'y':
        break
Run Code Online (Sandbox Code Playgroud)


Han*_*nto 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
Run Code Online (Sandbox Code Playgroud)


Jas*_*n L 5

有两种常用的方法,都已经提到过,相当于:

while True:
    do_stuff() # and eventually...
    break; # break out of the loop
Run Code Online (Sandbox Code Playgroud)

要么

x = True
while x:
    do_stuff() # and eventually...
    x = False # set x to False to break the loop
Run Code Online (Sandbox Code Playgroud)

两者都能正常运作.从"声音设计"的角度来看,最好使用第二种方法,因为1)break在某些语言的嵌套范围内可能具有违反直觉的行为; 2)第一种方法与"while"的预期用途相反; 3)你的例程应始终有一个退出点