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

前端 未结 4 1871
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 18:20

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 sa

相关标签:
4条回答
  • 2021-01-21 18:26

    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; 2) the first approach is counter to the intended use of "while"; 3) your routines should always have a single point of exit

    0 讨论(0)
  • 2021-01-21 18:33
    while True:
        func()
        answer = raw_input( "Loop again? " )
        if answer != 'y':
            break
    
    0 讨论(0)
  • 2021-01-21 18:40
    While raw_input("loop again? y/n ") != 'n':
        do_stuff()
    
    0 讨论(0)
  • 2021-01-21 18:42
    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
    
    0 讨论(0)
提交回复
热议问题