简体   繁体   English

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

[英]python - check at the end of the loop if need to run again

It's a really basic question but i can't think at the second. 这是一个非常基本的问题,但我不能在第二个问题上思考。 How do i set up a loop that asks each time the function inside runs whether to do it again. 我如何设置一个循环,每当内部函数运行时询问是否再次执行它。 So it runs it then says something like; 所以它运行它然后说类似的东西;

"loop again? y/n" “再次循环?y / n”

while True:
    func()
    answer = raw_input( "Loop again? " )
    if answer != 'y':
        break
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

There are two usual approaches, both already mentioned, which amount to: 有两种常用的方法,都已经提到过,相当于:

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

or 要么

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

Both will work properly. 两者都能正常运作。 From a "sound design" perspective it's best to use the second method because 1) break can have counterintuitive behavior in nested scopes in some languages; 从“声音设计”的角度来看,最好使用第二种方法,因为1) break在某些语言的嵌套作用域中可能具有违反直觉的行为; 2) the first approach is counter to the intended use of "while"; 2)第一种方法与“while”的预期用途相反; 3) your routines should always have a single point of exit 3)你的例程应始终有一个退出点

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM