26
votes

I'm using Python 3.2 and trying to exit it after the user inputs that they don't want to continue, is there code that will exit it in an if statement inside a while loop? I've already tried using exit(), sys.exit(), sys.quit(), quit(), and raise SystemExit.

1
all those should work? - Serial
Can you show us the code you're using where this doesn't work? Are you trying to exit the program, or just the if statement? Are you catching SystemExit for some reason? - Brendan Long
The only cases in which this could possibly fail are (a) not actually calling exit, (b) catching SystemExit or BaseException, (c) multithreading or multiprocessing, (d) really funky signal handling, or (e) embedded/custom Python interpreter. I strongly suspect it's (a). But if you don't give us your code (or, better, an SSCCE that minimally shows the same problem), we can't do more than suspect and guess. - abarnert
@ethan: It is impossible to format code in comments on SO. That makes it very hard to read (and also makes it impossible to diagnose indentation errors). Just edit your question and paste the properly-formatted code there. Also, please describe the actual input/output sequence that you're seeing. (For example, if you type "N", see "ok, sayonnara", but then don't exit, tell us exactly that.) - abarnert
@ChristianCareaga: I understand your frustration, but really, there's no harm here to anyone but the OP himself. If he never edits the question to become answerable, it'll just be closed (either in the present, or months later when someone searches for the same problem and finds a dead and useless question). - abarnert

1 Answers

43
votes

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input