tags:

views:

169

answers:

4

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?

+11  A: 

One way is to do:

sys.exit(0)

You will have to import sys of course.

Another way is to break out of your infinite loop. For example, you could do this:

while True:
    choice = get_input()
    if choice == "a":
        # do something
    elif choice == "q":
        break

Yet another way is to put your main loop in a function, and use return:

def run():
    while True:
        choice = get_input()
        if choice == "a":
            # do something
        elif choice == "q":
            return

if __name__ == "__main__":
    run()

The only reason you need the run() function when using return is that (unlike some other languages) you can't directly return from the main part of your Python code (the part that's not inside a function).

Greg Hewgill
For the sake of completeness: `raise SystemExit` would also work on its own (although not advised).
ChristopheD
@ChristopheD: I chose to omit discussion of exceptions, since they should not be used for normal program flow.
Greg Hewgill
@Greg: exceptions are not that exceptional in Python.
ΤΖΩΤΖΙΟΥ
+2  A: 

See sys.exit. That function will quit your program with the given exit status.

avpx
+1  A: 

In Python 3 there is an exit() function:

elif choice == "q":
    exit()
Roberto Bonvallet
I don't see that one in [Built-in Functions](http://docs.python.org/py3k/library/functions.html) - perhaps you're thinking of the one in [`sys`](http://docs.python.org/py3k/library/sys.html)?
Greg Hewgill
I don't see it either, but it does appear to work for me (Python 2.6)
harto
That's actually a concession for the interpreter mode - try `print(exit)` and see what you get. `quit` is similar.
Greg Hewgill
Both exit() and quit() seem to quit it in IDLE.P.S. How do you put stuff as code (i.e. functions) in comments?
Waterfox
`exit()` [is added by the `site` package](http://docs.python.org/py3k/library/constants.html?highlight=exit#constants-added-by-the-site-module). The documentation says it shouldn't be used in programs :$
Roberto Bonvallet
(@Greg: being in the `site` module means that it is not exclusive to the interactive interpreter)
Roberto Bonvallet
A: 

The actual way to end a program, is to call

raise SystemExit

It's what sys.exit does, anyway.

A plain SystemExit, or with None as a single argument, sets the process' exit code to zero. Any non-integer exception value (raise SystemExit("some message")) prints the exception value to sys.stderr and sets the exit code to 1. An integer value sets the process' exit code to the value:

$ python -c "raise SystemExit(4)"; echo $?
4
ΤΖΩΤΖΙΟΥ