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 Answer
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
11 Comments
ethan
already set up something similar and it didn't work. this is the code. if answer.lower().startswith("y"): print("ok, carry on then") elif answer.lower().startswith("n"): print("ok, sayonnara") sys.exit()
ducin
@ethan This solution is fair good enough. Paste your exact code here.
abarnert
I'd be very surprised if this actually works for you in Python 3.2. When I try it, I get the expected
NameError.abarnert
@tkoomzaaskz: Yes, I'm nearly 100% sure this code works. Sadly, I'm also 95% sure that it's not the OP's code (even though he implied that it was), or he wouldn't have had this question in the first place…
jkdev
It's recommended to use
import sys and then sys.exit() instead of the built-in exit(). See official docs and Difference between exit() and sys.exit() in Python. |
ifstatement? Are you catching SystemExit for some reason?exit, (b) catchingSystemExitorBaseException, (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.