For the "q" (quit) option in my program menu, I have the following code:
elif choice == "q":
print()
That worked all right until I put it in an infinite loop, which kept printing blank lines. Is there a method that can quit the program? Else, can you think of another solution?
The actual way to end a program, is to call
It's what
sys.exit
does, anyway.A plain
SystemExit
, or withNone
as a single argument, sets the process' exit code to zero. Any non-integer exception value (raise SystemExit("some message")
) prints the exception value tosys.stderr
and sets the exit code to 1. An integer value sets the process' exit code to the value:One way is to do:
You will have to
import sys
of course.Another way is to
break
out of your infinite loop. For example, you could do this:Yet another way is to put your main loop in a function, and use
return
:The only reason you need the
run()
function when usingreturn
is that (unlike some other languages) you can't directlyreturn
from the main part of your Python code (the part that's not inside a function).See
sys.exit
. That function will quit your program with the given exit status.In Python 3 there is an
exit()
function:Please note that the solutions based on sys.exit() or any Exception may not work in a multi-threaded environment.
This answer from Alex Martelli for more details.