tags:

views:

415

answers:

4

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"

+12  A: 
while True:
    func()
    answer = raw_input( "Loop again? " )
    if answer != 'y':
        break
Martin Cote
beat me to it. this is the one.
contagious
Haha, I am too slow as well :)
kigurai
+5  A: 
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
HanClinto
+1: formal exit condition without a break (Also, I removed the extra print)
S.Lott
Aaah, thanks S. Lott. I was racing, and missed that one -- thanks! :)
HanClinto
+3  A: 

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

Jason L
Now, if only you kept the two code bits and removed the final three paragraphs, I promise I will upvote you ;)
ΤΖΩΤΖΙΟΥ
There, I've made it more to the point. Just out of curiosity, was there something wrong with what I said or was it just how I said it?
Jason L
+1  A: 
While raw_input("loop again? y/n ") != 'n':
    do_stuff()
J.T. Hurley